how to check if List<T> element contains an item with a Particular Property Value

public class PricePublicModel
{
public PricePublicModel() { }


public int PriceGroupID { get; set; }
public double Size { get; set; }
public double Size2 { get; set; }
public int[] PrintType { get; set; }
public double[] Price { get; set; }
}


List<PricePublicModel> pricePublicList = new List<PricePublicModel>();

How to check if element of pricePublicList contains certain value. To be more precise, I want to check if there exists pricePublicModel.Size == 200? Also, if this element exists, how to know which one it is?

EDIT If Dictionary is more suitable for this then I could use Dictionary, but I would need to know how :)

302974 次浏览

使用 LINQ 很容易做到这一点:

var match = pricePublicList.FirstOrDefault(p => p.Size == 200);
if (match == null)
{
// Element doesn't exist
}
bool contains = pricePublicList.Any(p => p.Size == 200);
var item = pricePublicList.FirstOrDefault(x => x.Size == 200);
if (item != null) {
// There exists one with size 200 and is stored in item now
}
else {
// There is no PricePublicModel with size 200
}

如果您有一个列表,并且希望知道在列表中哪里存在匹配给定条件的元素,则可以使用 FindIndex实例方法。比如

int index = list.FindIndex(f => f.Bar == 17);

其中 f => f.Bar == 17是带匹配条件的谓词。

对你来说,你可以写

int index = pricePublicList.FindIndex(item => item.Size == 200);
if (index >= 0)
{
// element exists, do what you need
}

您实际上并不需要 LINQ,因为 List<T>提供了一个方法,可以完全满足您的需要: Find

搜索与指定谓词定义的条件相匹配的元素,并返回整个 List<T>中的第一个匹配项。

示例代码:

PricePublicModel result = pricePublicList.Find(x => x.Size == 200);

您可以使用存在的

if (pricePublicList.Exists(x => x.Size == 200))
{
//code
}

你也可以使用 List.Find():

if(pricePublicList.Find(item => item.Size == 200) != null)
{
// Item exists, do something
}
else
{
// Item does not exist, do something else
}