[ACCEPTED]-GroupBy with linq method syntax (not query syntax)-linq-query-syntax
It would look like this:
var query = checks
.GroupBy(c => string.Format("{0} - {1}", c.CustomerId, c.CustomerName))
.Select (g => new { Customer = g.Key, Payments = g });
0
First, the basic answer:
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 };
});
Then, how do you 18 figure out these things yourself?
First, download 17 Reflector from here, and install it.
Then build 16 a sample program, like a smallish console 15 program, containing the code you want to 14 analyze. Here's the code I wrote:
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 };
}
}
}
Then you 13 build that, and open reflector, and ask 12 it to open the .exe file in question.
Then 11 you navigate to the method in question, which 10 in my case was ConsoleApplication11.Program.Main
.
The trick here is to go 9 to the options page of Reflector, and ask 8 it to show C# 2.0 syntax, which will substitute 7 Linq with the appropriate static method 6 calls. Doing that gives me the following 5 code:
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 };
});
}
Now, of course this code can be written 4 a bit prettier with lambdas and similar, like 3 what @mquander showed, but with Reflector, at least you 2 should be able to understand the method 1 calls being involved.
I know this is a old question, but for new 3 readers, take a look at this gitub code.
This use Roslyn 2 to take query syntax and convert it to extension 1 method syntax.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.