Nidhin KR
Nidhin KR

Reputation: 21

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

Upvotes: 2

Views: 2358

Answers (5)

CodeHxr
CodeHxr

Reputation: 885

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.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160912

You can use linq to do this but not Contains

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

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245429

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500805

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
}

Upvotes: 5

Rei Miyasaka
Rei Miyasaka

Reputation: 7106

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

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

Upvotes: 6

Related Questions