How is a group in Linq with 2 fields?

as a group in Linq with 2 fields?

(from i in info 
 group i by i.OrderId into g 
 select new { orderId = g.Key, infos = g });

      

not only order with order Id, but also with two fields, for example ...

group by i.orderId And i.City

      

how will it do?

+1


a source to share


3 answers


I believe you want something like this:

var result = from i in info
             group i by new { OrderId = i.OrderId, City = i.City } into g
             select new { OrderId = g.Key, Infos = g };

      



Creating a key as an anonymous type simply allows LINQ to use the default equality mappings for all fields of the anonymous type, which should do the job in most situations.

+4


a source


In response to Noldorin's answer, you can omit the field names in the anonymous type when they match the fields you set for them.

Example:



var result = from i in info
             group i by new { i.OrderId, i.City } into g
             select new { OrderId = g.Key, Infos = g };

      

+3


a source


Another observation on Noldorin and Josh Einstein's answers ... OrderID will take over the entire key ... which in this case is a new object with two properties: OrderID and City. If your final result set requires OrderID to be the OrderID, you need to do the following:

var result = from i in info
             group i by new { i.OrderId, i.City } into g
             select new { OrderId = g.Key.OrderId, Infos = g };

      

+2


a source







All Articles