Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct on Multiple Columns Entity Framework LINQ

Tags:

What is the LINQ Equivalent of

Select DISTINCT A, B, C from TESTDB WHERE ALPHA =1 

I am trying something like this:

var data = TESTDB.WHERE(i=>i.ALPHA==1).SELECT(A,B,C).DISTINCT(); 
like image 567
Nanu Avatar asked Aug 06 '12 21:08

Nanu


2 Answers

Using anonymous objects will do the trick:

var data = TESTDB.Where(i => i.ALPHA == 1).Select(i => new {i.A, i.B, i.C}).Distinct(); 

To retain the model:

List<Book> books = db.Book.Select(i => new Book {Author = i.Author, Title = i.Title}).Distinct().ToList(); 
like image 152
Risky Martin Avatar answered Sep 23 '22 12:09

Risky Martin


You can also try

db.Table   .OrderBy(m=>m.Name)   .DistinctBy(m=> new{m.SerialNumber, m.Manufacturer})   .ToList(); 
like image 27
sherebry Avatar answered Sep 25 '22 12:09

sherebry