等价的linq查询语法

时间:2018-03-26 21:16:29

标签: c# linq

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时出现了这个问题。

1 个答案:

答案 0 :(得分:4)

groupby之间的表达式是元素选择器。您不遗余力地将添加您特别不想要的信息添加到该元素中。你只需要......不要那样做。

var groups = from product in products
             from category in product.Categories
             group product by category into g
             select g;