Distinct not working in entity framework

c# entity-framework-6

Question

function for get list of documents name only with distinct...

public static List<DocumentTypeModel> GetUploadedDocumentsName(int TicketId)
{
    List<DocumentTypeModel> documents = new List<DocumentTypeModel>();
    using (var db = new UnitOfWork())
    {
        documents = db.tbl_TrnTicketDocument.Get(x => x.FK_TicketId == TicketId && x.IsActive == true).Select(s => new DocumentTypeModel()
        {
            DocumentTypeNameEnglish = s.tbl_MstDocumentType.DocumentTypeNameEnglish
        }).Distinct().ToList();
    }
    return documents;
}

currently result is this -

Affidavit in Case of Cancelled Will/No Will

Affidavit in Case of Cancelled Will/No Will

Allotment Letter

Allotment Letter

Death Certificate

Death Certificate

Lease Deed

Lease Deed

Photo Identity of Applicant

Photo Identity of Applicant

Possession Letter

Possession Letter

Registered/Unregistered Will

Registered/Unregistered Will

1
3
3/30/2016 12:25:04 PM

Accepted Answer

You can use groupby and select first option like this:

List<DocumentTypeModel> documents = new List<DocumentTypeModel>();
using (var db = new UnitOfWork())
{
   documents = db.tbl_TrnTicketDocument.Get(x => x.FK_TicketId == TicketId && x.IsActive == true).Select(s => new DocumentTypeModel()
   {
   DocumentTypeNameEnglish = s.tbl_MstDocumentType.DocumentTypeNameEnglish
   }).ToList();

   documents = documents.GroupBy(x => x.DocumentTypeNameEnglish).Select(g => g.First());
}
10
3/30/2016 11:45:50 AM

Popular Answer

Distinct() doesn't work like you tried on objects. Use IComparer to get this working https://support.microsoft.com/en-us/kb/320727

Create a comparer class

public class DocumentTypeModelComparer: IComparer
{
  int IComparer.Compare(object a, object b)
 {
   if(a.Id == b.ID)
     return 0;
   else
     return 1;
  }
}

Now in your lambda expression

 documents = db.tbl_TrnTicketDocument.Get(x => x.FK_TicketId == TicketId && x.IsActive == true).Select(s => new DocumentTypeModel()
        {
            DocumentTypeNameEnglish = s.tbl_MstDocumentType.DocumentTypeNameEnglish
        }).ToList().Distinct(new DocumentTypeModelComparer()).ToList();



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow