如果我使用扩展方法语法,以下查询将如何显示?
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 }
如果我使用扩展方法语法,以下查询将如何显示?
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 }
它看起来像这样:
var query = checks
.GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
.Select (g => new { Customer = g.Key, Payments = g });
首先,基本答案:
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 };
});
那么,你如何自己弄清楚这些事情呢?
首先,从这里下载 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 展示的那样,但是使用 Reflector,至少你应该能够理解所涉及的方法调用。
由于编译器会为您执行此翻译,请启动Reflector并查看一下。
我知道这是一个老问题,但是对于新读者来说,看看这个 gitub代码。
这使用 Roslyn 获取查询语法并将其转换为扩展方法语法。