Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check if any value exists on ArrayList

Tags:

c#

.net

I have ArrayList. I want to check if any value exits in t his ArrayList. I would like to use Any method (from System.Linq namespace), but I can use it only on Array, not ArrayList.

Is there any efficient way to check this?

like image 231
GrzesiekO Avatar asked Jan 13 '23 13:01

GrzesiekO


2 Answers

Well, you could check the .Count > 0. But a better option would be stop using ArrayList. Since you know about Any() and System.Linq, I assume you're not using .NET 1.1; so use List<T> for some T, and all your problems will be solved. This has full LINQ-to-Objects usage, and is just a much better idea.

List<int> myInts = ...
bool anyAtAll = myInts.Any();
bool anyEvens = myInts.Any(x => (x % 2) == 0);
// etc
like image 139
Marc Gravell Avatar answered Jan 17 '23 16:01

Marc Gravell


use the link .Cast method to cast your array list to a generic type

ArrayList ar = new ArrayList();

bool hasItem = ar.Cast<int>().Any( i => i == 1);
like image 45
Sam I am says Reinstate Monica Avatar answered Jan 17 '23 18:01

Sam I am says Reinstate Monica