Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinct not working in entity framework

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

like image 357
Lokesh Avatar asked Mar 30 '16 11:03

Lokesh


2 Answers

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());
}
like image 51
Navoneel Talukdar Avatar answered Oct 20 '22 16:10

Navoneel Talukdar


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();

like image 1
M.S. Avatar answered Oct 20 '22 15:10

M.S.