views:

966

answers:

1

How do you group by multiple columns in LINQ TO SQL?

db.Table.GroupBy(a => a.column1.ToString() + a.column2.ToString())

It seems ugly and with poor performance, and I don't even know if it works. Which is the right way to do it?

+4  A: 

try grouping by an anonymous type:

group by new { item.Col1, item.Col2 }

you'll then be able to access Key.Col1, etc

David Hedlund
Does it works? AnonTypes implement Equals and GetHashCode automatically so you don't have to worry about it?
Jader Dias
Just tested it, and you're right. Test code: var a = new { A = 1, B = 2 }; var b = new { A = 1, B = 2 }; var c = new { A = 1, B = 3 }; Assert.AreEqual(a, b); Assert.AreNotEqual(a, c);
Jader Dias
yeah it works, it's the official way. here's a good reference: http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx
David Hedlund