简体   繁体   中英

linq difference between two select count queries

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

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM