given the following information I have in a database table:
Col 1, Col2, Col3
1 , x , G
1 , y , H
2 , z , J
2 , a , K
2 , a , K
3 , b , E
What can I do in Linq (as I'm using Entity Framework) to get the following:
1 , x , G
1 , y , H
2 , z , J
2 , a , K
3 , b , E
You get the idea, I can do it in SQL just fine with the following:
Select Col 1, Col 2, Col 3
from Table
group by Col 1, Col 2, Col 3
No Idea how to do it in code as I can only find a way to do a distinct on one column.
Try this :
var Result = Context.Table.Select(C =>
new {
Col1 = C.Col1,
Col2 = C.Col2,
Col3 = C.Col3 }).Distinct();
Or alternately :
var Result = Context.Table.GroupBy(G=> new { G.Col1, G.Col2, G.Col3 })
.Select(C => new {
Col1 = C.Key.Col1,
Col2 = C.Key.Col2,
Col3 = C.Key.Col3
});
You could also use group by in linq on multiple fields:
myList.GroupBy(x=>new {x.Col1,x.Col2,x.Col3}).Select(x=>x.First()).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With