Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq ambiguity on where and select

Today I ran into an issue with LINQ to objects (not SQL) that popped up due to a typo. I had a .Select one place and a .Where in another place. I was expecting same result but they are showing different numbers. Assume somelist has 10 elements with all elements having qty = 0

//returns 10 - basically count of all rows. I am expecting 0
 somelist.Select(p => p.qty > 0).Count() 

//returns 0 - the correct count
 somelist.Where(p => p.qty > 0).Count() 

if both select and where return IEnumerable<T> then why the ambiguity? Thank you.

like image 351
Gullu Avatar asked Nov 15 '11 20:11

Gullu


2 Answers

Select is a projection, so what you get is the expression p.qty > 0 evaluated for each element in somelist. i.e. lots of true/false values (the same number as your original list). So when you do Count on it, you get the same number. If you look the select will return IEnumerable<bool> (because the type of p.qty > 0 is a bool).

Where filters the results so count runs on the filtered list, and give you the expected results. The type of this is an IEnumerable<TypeOfElementInOriginalList>.

Note you can also do: somelist.Count(p => p.qty > 0) because Count has an overload that accepts a predicate to filter by.

like image 86
George Duckett Avatar answered Nov 16 '22 07:11

George Duckett


The first query gives the same as somelist.Count(). It's just the number of elements in the sequence. The call to Select projects each object, but the number of objects remains the same.

The second query gives the number of elements that fulfil the predicate, which is a potentially lower number. The call to Where filters objects from the sequence.

like image 43
Mark Byers Avatar answered Nov 16 '22 08:11

Mark Byers