等效的linq查询语法 [英] Equivalent linq query syntax

查看:53
本文介绍了等效的linq查询语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下GroupBy重载的等效查询语法是什么:

What is the equivalent query syntax for the following overload of GroupBy:

public static IEnumerable<IGrouping<TKey, TElement>> 
   GroupBy<TSource, TKey, TElement>(
      this IEnumerable<TSource> source,
      Func<TSource, TKey> keySelector,
      Func<TSource, TElement> elementSelector
)

在尝试编写以下等效查询语法时出现了这个问题:

This question cropped up when trying to write the equivalent query syntax of the following:

var groups = 
    products.SelectMany(p => p.Categories,
                    (p, c) => new { Product = p, Category = c })
            .GroupBy(p => p.Category, p => p.Product);

普通"查询语法将提供冗余信息:Category已由Key属性提供:

The "normal" query syntax would give back redundant information: Category already given by the Key property:

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 issue cropped up while answering this question.

推荐答案

groupby之间的表达式是元素选择器.您将添加明确不想要的信息添加到该元素中.您只需要...不需要这样做.

The expression between group and by is the element selector. You went out of your way to add the information you specifically don't want into that element. You just need to...not do that.

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

这篇关于等效的linq查询语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆