Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the fastest way to check IEnumerable Count is greater than zero without loop through all records

Tags:

c#

ienumerable

i know everyone says to avoid doing something like this because its very slow (just to find out if there is 0)

  IEnumerable<MyObject> list;
  if (list.Count() > 0)
  { 
  }

but what is the best alternative when all i need to do is find out if the list has a count of 0 or if there are items in it

like image 483
leora Avatar asked Dec 21 '22 14:12

leora


1 Answers

Use list.Any(). It returns true if it finds an element. Implementation wise, it would be:

using (var enumerator = list.GetEnumerator())
{
  return enumerator.MoveNext();
}
like image 105
Femaref Avatar answered Jan 04 '23 23:01

Femaref