如果我使用扩展方法语法,以下查询将如何呈现?
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 };
});
}