Perlnika
Perlnika

Reputation: 5066

C# how to determine, whether ArrayList contains object with certain attribute

I have an ArrayList of objects of my custom class. I would like to know, if ArrayList contains object with certain attribute. I do not care about the object, just if there is some. Yes, I could do this with foreach cycle, but I was wondering if there was more elegant way to do so.

Thanks for suggestions.

Upvotes: 2

Views: 4753

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500765

Well, to start with I'd suggest using List<T> instead of ArrayList. Then LINQ to Objects makes it really easy:

if (list.Any(x => x.HasFoo))
{
}

Or without LINQ (but still List<T>)

if (list.FindIndex(x => x.HasFoo) != -1)
{
}

If you really need to stick with a non-generic collection but have LINQ to Objects available too, you can use:

if (arrayList.Cast<YourType>().Any(x => x.HasFoo))
{
}

Upvotes: 8

Mario Corchero
Mario Corchero

Reputation: 5575

use Linq:

var query = from o in yourarray select o where o.atribute==ValueIWant;


`query.Count()` will return the number of objects that fit the condition.

check that msdn example: Linq example

Upvotes: -1

Related Questions