2

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.

Perlnika
  • 4,796
  • 8
  • 36
  • 47

2 Answers2

8

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))
{
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Why do people so often confuse extension methods with LINQ? LINQ as per the name is a language integrated query of the form: from x in collection where condition select... which can be translated to a method chain like collection.Where(x=>condition).Select(x=>stuff) – edvaldig Feb 15 '12 at 11:35
  • @edvaldig: It's more than that - it's a whole collection of technologies. This is using LINQ to Objects, for example. I'll happily update the answer to clarify that, but I think it's still reasonable to say this code is "using LINQ". – Jon Skeet Feb 15 '12 at 11:37
  • Thank you. First variant is exactly what I wanted! I also replaced ArrayList with List so that I have all functionality I need. – Perlnika Feb 15 '12 at 11:54
-1

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

Mario Corchero
  • 5,257
  • 5
  • 33
  • 59
  • That won't compile (select before where), would be inelegant if it did (the query expression is more verbose than just a single `Where` call), and would be inefficient (using `Count()` instead of `Any()` requires testing against the whole collection, instead of stopping when it finds the first match. Oh, and you'd need `Cast<>` or an explicitly typed range variable to work with `ArrayList` in the first place... – Jon Skeet Feb 15 '12 at 11:33