在 BindingList<T> 中查找

8
如何在BindingList中查找具有特定属性值的对象。以下是我的代码。
public class Product
{
    public int ProductID { get; set; } 
    public string ProductName { get; set; }  
}

BindingList<Product> productList = new BindingList<Product>();

现在假设产品列表有100个产品,我想找到id为10的产品对象。 我可以使用:
productList.ToList<Product>().Find(p =>p.ProductID == 1);

但我觉得在这里使用ToList()是不必要的开销。有没有直接的方法来做到这一点?BindingList<T>中没有'Find'方法。

1个回答

16

你可以使用LINQ中的SingleOrDefault方法代替Find

Product product = productList.SingleOrDefault(p => p.ProductID == 1);
如果没有这样的产品,product 将为null。如果有多个匹配项,则会抛出异常。 你应该真正了解LINQ to Objects-它使许多数据操作显着更简单。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接