开发者

ArrayList C# Contains method query

I have an ObservableCollection<myClass> list. It contains a 10 objects of type MyClass.

class MyClass
{
  string name;
  int age;
}

If I want to find all items in list where age = 10, can I use the Contains method? If yes 开发者_C百科how can I do this without using iteration?


var age10 = list.Where(i => i.age == 10);

Lots more queries here: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx


No, Contains only looks for a specific value, not something matching a predicate. It also only finds one value rather than every matching value.

You can, however, use Where from LINQ to Objects, assuming you're on .NET 3.5 or higher:

foreach (var item in list.Where(x => x.Age == 10))
{
    // Do something with item
}


Since ObservableCollection<T> implements Collection<T> which implements IEnumerable<T>...you can use the LINQ to Object extension methods to make this simple (even though it will use iteration in the background):

var results = list.Where(m => m.age == 10);


As others have stated, using .Where(i => i.Age == 10) would be the correct way to get the result stated in the question. You would use .Contains() to check your collection for a specific instance of your class.


You can use linq to do this but not Contains

 var foo = from bar in myCollection where bar.age == 10 select bar;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜