NIlesh Lanke NIlesh Lanke - 1 year ago 68
C# Question

Search within a list in C#

I have a list containing the following structure.

class CompareDesignGroup
string FieldId;
string Caption;

The list is containing items of the above structure.

Is it possible to retrieve an element of the list if FieldId is known?

Answer Source

You can use the Find method on the generic list class. The find method takes a predicate that lets you filter/search the list for a single item.

List<CompareDesignGroup> list = // ..;
CompareDesignGroup item = list.Find(c => c.FieldId == "SomeFieldId");

item will be null if there is no matching item in the list.

If you need to find more than one item you can use the FindAll method:

List<CompareDesignGroup> list = // ..;
List<CompareDesignGroup> result= list.FindAll(c => c.FieldId == "SomeFieldId");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download