[英]C# Linq -Extension Method
How to use extension methods to form the second query as the first one. 如何使用扩展方法将第二个查询形成为第一个查询。
1) var query = from cm in cust
group cm by cm.Customer into cmr
select (new { CKey = cmr.Key, Count = cmr.Count() });
(second query is not well formed) (第二个查询形式不正确)
2) var qry = cust.GroupBy(p => p.Customer).
Select(new { CKey = p.Key, Count = p.Count });
Try this: 尝试这个:
var query = cust.GroupBy(p => p.Customer)
.Select(g => new { CKey = g.Key, Count = g.Count() });
You can also simplify this into a single call to this GroupBy
overload though: 您也可以将此简化为对此GroupBy
重载的单个调用,但:
var query = cust.GroupBy(p => p.Customer,
(key, g) => new { CKey = key, Count = g.Count() });
Note that I've changed the name of the lambda expression's parameter name for the second line to g
- I believe that gives more of a clue that you're really looking at a group rather than a single entity. 请注意,我已将第二行的lambda表达式参数名称的名称更改为g
- 我相信这给出了更多的线索,表明您实际上是在查看组而不是单个实体。
I've also moved the dot onto the second line in the form that still uses Select
- I find this makes the query easier to read; 我还将点移动到仍然使用Select
的形式的第二行 - 我发现这使查询更容易阅读; I usually line up the dots, eg 我通常排列点,例如
var query = foo.Where(...)
.OrderBy(...)
.GroupBy(...)
.Select(...)
I think you need: 我想你需要:
var qry = cust.GroupBy(p => p.Customer)
.Select(grp => new { CKey = grp.Key, Count = grp.Count() });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.