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.
Selectis a projection, so what you get is the expressionp.qty > 0evaluated for each element insomelist. i.e. lots of true/false values (the same number as your original list). So when you doCounton it, you get the same number. If you look the select will returnIEnumerable<bool>(because the type ofp.qty > 0is a bool).Wherefilters the results so count runs on the filtered list, and give you the expected results. The type of this is anIEnumerable<TypeOfElementInOriginalList>.Note you can also do:
somelist.Count(p => p.qty > 0)because Count has an overload that accepts a predicate to filter by.