Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to see if IEnumerable<T> contains item based on criteria

Tags:

contains

linq

Sort of a Linq beginners question, but is there a simple built-in way to optimize this:

bool containsItemWithValue42 = items.Where(i => i.Value == 42).Count() > 0;

I would like Linq to stop iterating as soon as it found a match.

like image 827
bitbonk Avatar asked Dec 17 '22 21:12

bitbonk


1 Answers

The Any method does exactly that:

bool containsItemWithValue42 = items.Any(i => i.Value == 42);
like image 65
Fredrik Mörk Avatar answered Jan 13 '23 14:01

Fredrik Mörk