Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct not working with LINQ [duplicate]

Tags:

c#

linq

I want to remove repeated rows from a LIST using distinct.

This is the resultset (As you can see, index 12 and 14 are repeated)

id  idIndice    idName         idTipo   tamanho     caminho
12  11          Processo       3        10          C:\Program Files\Empenho\Senha.txt
13  13          Endereço       1        250         C:\Program Files\Empenho\Senha.txt
14  12          Número         2        5           C:\Program Files\Empenho\Senha.txt
15  9           Cep            5        8           C:\Program Files\Empenho\Senha.txt 
16  10          Dt. de Nasc.   4        0           C:\Program Files\Empenho\Senha.txt
12  11          Processo       3        10          C:\Program Files\Empenho\Senha.txt
14  12          Número         2        5           C:\Program Files\Empenho\Senha.txt

This is the sql I want to archieve (this does the job)

select DISTINCT u.id, u.idIndice, t.idName, t.idTipo, t.tamanho, l.caminho
from  tgpwebged.dbo.sistema_Indexacao as u
join  tgpwebged.dbo.sistema_Indexes as t on u.idIndice = t.id
join  tgpwebged.dbo.sistema_Documentos as l on u.idDocumento = l.id
join  tgpwebged.dbo.sistema_DocType_Index as v on t.id = v.indexId
where u.idDocumento = 10 

This is the LINQ I am trying to adapt

var docObj = from u in context.sistema_Indexacao
join t in context.sistema_Indexes on u.idIndice equals t.id
join l in context.sistema_Documentos on u.idDocumento equals l.id
join v in context.sistema_DocType_Index on t.id equals v.indexId
join m in context.sistema_DocType on v.docTypeId equals m.id
where u.idDocumento == id
select new Gedi.Models.OperacoesModel.getDocIndex
{ ...  };

This is what I am trying:

List<Gedi.Models.OperacoesModel.getDocIndex> docIndexModelDup = docObj.ToList();
List<Gedi.Models.OperacoesModel.getDocIndex> docIndexModel =
docIndexModelDup.Distinct().ToList();

But I still get the same 7 rows as if there is no DISTINCT at all.

Why?

like image 580
Dimas Longo Avatar asked Dec 19 '12 13:12

Dimas Longo


2 Answers

If you want the Distinct performed in sql, call Distinct() before ToList().

var docObj = (from u in context.sistema_Indexacao
    join t in context.sistema_Indexes on u.idIndice equals t.id
    join l in context.sistema_Documentos on u.idDocumento equals l.id
    join v in context.sistema_DocType_Index on t.id equals v.indexId
    join m in context.sistema_DocType on v.docTypeId equals m.id
    where u.idDocumento == id
    select new Gedi.Models.OperacoesModel.getDocIndex
    { ...  }).Distinct().ToList();
like image 99
jrummell Avatar answered Oct 07 '22 19:10

jrummell


var docIndexModel = docIndexModelDup
    .GroupBy(x => x.Id)
    .Select(g => g.First());
like image 5
Christoffer Lette Avatar answered Oct 07 '22 19:10

Christoffer Lette