Find in BindingList<T>
Asked Answered
S

1

8

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>

Sutra answered 28/7, 2012 at 11:40 Comment(0)
E
16

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.

Elata answered 28/7, 2012 at 11:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.