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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With