简体   繁体   English

linq两个选择计数查询之间的差异

[英]linq difference between two select count queries

I'm trying to learn about linq queries. 我正在尝试了解linq查询。 I have a list _taskDetail which contains 8 elements. 我有一个包含8个元素的_taskDetail列表。 I do not understand why the first query below returns the answer 8? 我不明白为什么下面的第一个查询返回答案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? 是的,列表包含8个元素,但所有td.Names不同,并且我指定了td.Name == taskName,所以为什么它返回所有内容,即使td.Name不等于taskName的元素也是如此?

The second query gives me the expected and correct answer of 1. 第二个查询给了我预期的正确答案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. 第一个版本没有意义,您需要一个Where ,而不是一个Select ,它是一个投影,而不是一个过滤器。

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. 在第一个版本中,Select将返回IEnumerable<bool> (对于列表中的每个项目,如果Name == taskName ,它将返回true,否则返回false。因此,将返回所有项目,并且计数将得出你...清单的数目。

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. Select仅产生投影,它不过滤结果。 The correct way to execute is using Where instead of Select ... 正确的执行方法是使用Where而不是Select ...

var Ans1 = _taskDetail.Where(td => td.Name == taskName).Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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