开发者

Finding Class Elements in a List of Classes

I am tryin开发者_开发技巧g 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.


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");


Use the where extension method:

var items = myClassList.Where(x => x.item1 == "abc");

The above snippet will return all objects with property item1 equal to "abc".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜