Reputation: 6668
I'm trying to learn about linq queries. I have a list _taskDetail which contains 8 elements. I do not understand why the first query below returns the answer 8? Yes the list contains 8 elements but all the td.Names are different and I have specified td.Name == taskName so why is it returning everything even elements where the td.Name does not equal taskName?
The second query gives me the expected and correct answer of 1.
var Ans1 = _taskDetail.Select(td => td.Name == taskName).Count();
var Ans2 = (from tdList in _taskDetail
where tdList.Name == taskName
select tdList).Count();
Ans1 = 8
Ans2 = 1
Upvotes: 1
Views: 127
Reputation: 60503
The first version doesn't make sense, you need a Where
, and not a Select
which is a projection, not a filter.
The Select, in the first version, will return you an IEnumerable<bool>
(for each item in the list, it will return true if Name == taskName
and false if not. So all items will be returned, and the count will give you... the count of the list.
so
_taskDetail.Where(td => td.Name == taskName).Count();
By the way, you can simply do
_taskDetail.Count(td => td.Name == taskName);
Detail to maybe understand better
The second (wrong) version (query syntax) corresponding to your actual (wrong) first version (method syntax) would be
(from tdList in _taskDetail
select tdList.Name == taskName).Count();
Upvotes: 5
Reputation: 14850
It's because the first query is wrong. Select
only produces a projection, it does NOT filter the results. The correct way to execute is using Where
instead of Select
...
var Ans1 = _taskDetail.Where(td => td.Name == taskName).Count();
Upvotes: 2