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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With