GroupBy with linq方法语法(不是查询语法)

时间:2009-06-08 21:21:35

标签: c# linq translation linq-query-syntax

如果我使用扩展方法语法,以下查询将如何显示?

var query = from c in checks
group c by string.Format("{0} - {1}", c.CustomerId, c.CustomerName) 
into customerGroups
select new { Customer = customerGroups.Key, Payments = customerGroups }

4 个答案:

答案 0 :(得分:24)

看起来像这样:

var query = checks
    .GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
    .Select (g => new { Customer = g.Key, Payments = g });

答案 1 :(得分:8)

首先,基本答案:

var query = checks.GroupBy<Customer, string>(delegate (Customer c) {
    return string.Format("{0} - {1}", c.CustomerId, c.CustomerName);
}).Select(delegate (IGrouping<string, Customer> customerGroups) {
    return new { Customer = customerGroups.Key, Payments = customerGroups };
});

然后,你如何自己弄清楚这些事情?

首先,从here下载Reflector,然后安装它。

然后构建一个示例程序,就像一个小型控制台程序,包含您要分析的代码。这是我写的代码:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication11
{
    public class Customer
    {
        public Int32 CustomerId;
        public Int32 CustomerName;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var checks = new List<Customer>();
            var query = from c in checks
                        group c by String.Format("{0} - {1}", c.CustomerId, c.CustomerName)
                            into customerGroups
                            select new { Customer = customerGroups.Key, Payments = customerGroups };
        }
    }
}

然后构建它,并打开反射器,并要求它打开有问题的.exe文件。

然后导航到相关方法,在我的例子中是ConsoleApplication11.Program.Main

这里的技巧是转到Reflector的选项页面,并要求它显示C#2.0语法,它将用适当的静态方法调用替换Linq。这样做会给我以下代码:

private static void Main(string[] args)
{
    List<Customer> checks = new List<Customer>();
    var query = checks.GroupBy<Customer, string>(delegate (Customer c) {
        return string.Format("{0} - {1}", c.CustomerId, c.CustomerName);
    }).Select(delegate (IGrouping<string, Customer> customerGroups) {
        return new { Customer = customerGroups.Key, Payments = customerGroups };
    });
}

现在,当然这段代码可以用lambdas和类似的东西写得更漂亮,比如@mquander showed,但是使用Reflector,至少你应该能够理解涉及的方法调用

答案 2 :(得分:2)

由于编译器会为您执行此翻译,请启动Reflector并查看。

答案 3 :(得分:1)

我知道这是一个老问题,但对于新读者,请查看this gitub代码。

这使用Roslyn来获取查询语法并将其转换为扩展方法语法。