Find Method on Generic List

F

Fresno Bob

I have a generic collection of objects and I would like to find the object
by one of it's properties e.g. I would like something with the functionality
of something like list.find(Customer.CustomerID = 1). Is there an easy way
to do this. The stuff with predicates and findall is a little confusing.
 
G

Göran Andersson

Fresno said:
I have a generic collection of objects and I would like to find the object
by one of it's properties e.g. I would like something with the functionality
of something like list.find(Customer.CustomerID = 1). Is there an easy way
to do this. The stuff with predicates and findall is a little confusing.

I hope this cures some of your confusion:

The FindAll method uses a delegate, so you can just make a method and
use with the FindAll method:

public static bool FindCustomerOne(Customer c) {
return c.CustomerID == 1;
}

List<Customer> result = myCustomerList.FindAll(FindCustomerOne);

The FindAll method will just loop through all the items in the list and
call the FindCustomerOne method for each one to determine which one to
return in the result.


You can also do the same with an anonymous method:

List<Customer> result = myCustomerList.FindAll(
delegate(Customer c){ return c.CustomerID == 1; }
);


If you are using C# 3, you can also use a lambda expression to do the same:

List<Customer> result = myCustomerList.FindAll(c => c.CustomerID == 1);
 
G

Göran Andersson

Sorry about the C# code. Didn't look to carefully where I was. You can
do the same with VB using the AddressOf keyword to send a delegate to
the FindAll method.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top