In primo luogo, la risposta di base:
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 };
});
Quindi, come si fa a capire queste cose da soli?
Per prima cosa, scaricare Reflector da here e installarlo.
Quindi creare un programma di esempio, come un programma console di piccole dimensioni, contenente il codice che si desidera analizzare. Ecco il codice che ho scritto:
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 };
}
}
}
poi si costruisce questo, e riflettore aperto, e le chiede di aprire il file exe in questione.
Quindi si passa al metodo in questione, che nel mio caso era ConsoleApplication11.Program.Main
.
Il trucco qui è di andare alla pagina delle opzioni di Reflector e chiedergli di mostrare la sintassi C# 2.0, che sostituirà Linq con le chiamate al metodo statico appropriate. In questo che mi dà il seguente codice:
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 };
});
}
Ora, naturalmente questo codice può essere scritto un po 'più carina con lambda e simili, come quello che @mquandershowed, ma con riflettore, almeno si dovrebbe essere in grado di capire la chiamate di metodo coinvolte.
Per il vostro riferimento futuro, questa domanda ha una risposta nella specifica C# 3.0, che è possibile scaricare da Internet. Qui sono specificate tutte le regole di trasformazione della query. –
ty, non sapeva che le regole di trasformazione erano state documentate. –