Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find in BindingList<T>

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>

like image 681
krishnan Avatar asked Jul 28 '12 11:07

krishnan


1 Answers

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.

like image 129
Jon Skeet Avatar answered Sep 23 '22 18:09

Jon Skeet