tags:

views:

294

answers:

3

how group by in Linq with 2 Field ?

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

not only order by with order Id but with two field like ...

group by i.orderId And i.City

how this will do?

+3  A: 

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 the key as an anonymous type simply allows LINQ to use the default equality comparers for all the fields of the anonymous type, which should do the job in most situations.

Noldorin
It's also very helpful to open Reflector on a compiled app that uses an anonymous type like this because it helps to understand why the above works. It's also not a bad guideline for when you need to create non-anonymous types how you should implement Equals(), GetHashCode(), etc...
Josh Einstein
@Josh: Yeah, that's probably a good recommendation. Saying that, you can often (and need to) do a lot better than using default comparers in user-defined types.
Noldorin
+2  A: 

As a follow-up to Noldorin's answer, you can omit the field names on the anonymous type when they match the fields you're setting them to.

Example:

var result = from i in info
             group i by new { i.OrderId, i.City } into g
             select new { OrderId = g.Key, Infos = g };
Josh Einstein
+1  A: 

Another follow-up to the Noldorin's and Josh Einstein's answers...OrderID will take on the entire key...which in this case is a new object with two properties, OrderID and City. If your final result set needs the OrderID to be the OrderID, then you'll 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 };
jrista