【发布时间】:2018-03-26 21:16:29
【问题描述】:
GroupBy 的以下重载的等效查询语法是什么:
public static IEnumerable<IGrouping<TKey, TElement>>
GroupBy<TSource, TKey, TElement>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
Func<TSource, TElement> elementSelector
)
在尝试编写以下等效查询语法时出现了这个问题:
var groups =
products.SelectMany(p => p.Categories,
(p, c) => new { Product = p, Category = c })
.GroupBy(p => p.Category, p => p.Product);
“正常”查询语法会返回冗余信息:Category 已由 Key 属性给出:
var groups = from p in products
from c in p.Categories
let pc = new { Product = p, Category = c }
group pc by pc.Category into g
select g;
相当于:
var groups =
products.SelectMany(p => p.Categories,
(p, c) => new { Product = p, Category = c })
.GroupBy(p => p.Category);
回复this question时出现此问题。
【问题讨论】: