Dan*_*nor 19 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 }
Run Code Online (Sandbox Code Playgroud)
mqp*_*mqp 24
它看起来像这样:
var query = checks
.GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
.Select (g => new { Customer = g.Key, Payments = g });
Run Code Online (Sandbox Code Playgroud)
一,基本答案:
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 };
});
Run Code Online (Sandbox Code Playgroud)
那你怎么自己弄清楚这些东西呢?
首先,从这里下载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 };
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你构建它,并打开反射器,并要求它打开有问题的.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 };
});
}
Run Code Online (Sandbox Code Playgroud)
现在,当然这个代码可以用lambdas和类似的东西写得 更漂亮,就像@mquander所展示的那样,但是使用Reflector,至少你应该能够理解所涉及的方法调用.