Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Class Elements in a List of Classes

Tags:

c#

find

list

I am trying to use the "List.Find" method to find a match with an element in my class. Here is an example...

class MyClass
{
    String item1;
    String item2;
}

List<MyClass> myClassList = new List<MyClass>();

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????

Anyway, I hope that explains a bit better. I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

like image 934
Eric Avatar asked Dec 20 '10 17:12

Eric


1 Answers

Your example is almost there. You should probably be using the FindAll method:

List<MyClass> results = myClassList.FindAll(x => x.item1 == "abc");

Or, if you prefer your results to be typed as IEnumerable<T> rather than List<T>, you can use LINQ's Where method:

IEnumerable<MyClass> results = myClassList.Where(x => x.item1 == "abc");
like image 132
LukeH Avatar answered Sep 28 '22 16:09

LukeH