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);
&#34;正常&#34;查询语法将返回冗余信息: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时出现了这个问题。
答案 0 :(得分:4)
group
和by
之间的表达式是元素选择器。您不遗余力地将添加您特别不想要的信息添加到该元素中。你只需要......不要那样做。
var groups = from product in products
from category in product.Categories
group product by category into g
select g;