Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Distincts with Linq

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.

like image 670
user1266921 Avatar asked Jan 28 '26 11:01

user1266921


2 Answers

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 
                                            });
like image 158
Kundan Singh Chouhan Avatar answered Jan 31 '26 14:01

Kundan Singh Chouhan


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();
like image 44
Saeed Amiri Avatar answered Jan 31 '26 13:01

Saeed Amiri