Find in BindingList<T>

krishnan picture krishnan · Jul 28, 2012 · Viewed 13.7k times · Source

How to find an object in BindingList that has a property equals to specific value. Below is my code.

public class Product
{
    public int ProductID { get; set; } 
    public string ProductName { get; set; }  
}

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

now consider that the productList has 100 products and i want to find the product object whose id is 10.

I can find it using

productList.ToList<Product>().Find(p =>p.ProductID == 1);

but i feel using ToList() is an unwanted overheard here. Is there any direct way to do this, there is no 'Find' method in BindingList<T>

Answer

Jon Skeet picture Jon Skeet · Jul 28, 2012

You can use SingleOrDefault from LINQ instead of Find:

Product product = productList.SingleOrDefault(p => p.ProductID == 1);

product will be null if there were no such products. If there's more than one match, an exception will be thrown.

You should really look into LINQ to Objects - it makes many operations on data significantly simpler.