views:

66

answers:

4

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 how can I do this without using iteration?

+6  A: 
var age10 = list.Where(i => i.age == 10);

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

Rei Miyasaka
Note that while this is a fine solution, behind the scenes it uses iteration. Thats no problem for 10 objects, but can be slow if overused on larger collections, so be aware of it.
Eamon Nerbonne
Actually, iterators are slow in cases where the time cost of iteration is more significant than the time cost of processing each value in the loop, *and* the collection is large (up in the hundreds). If that's the case though, you'd likely want to reconsider your choice of data structure to begin with: a sorted native array, a tree, or a dictionary of lists would fare better, as they'd be O(log N), O(log N) and O(1) for searching respectively -- as opposed to the O(N) you get with an unsorted ObservableCollection.
Rei Miyasaka
+5  A: 

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
}
Jon Skeet
+3  A: 

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);
Justin Niessner
A: 

You can use linq to do this but not Contains

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