Search code examples
c#linqasqueryable

Using Distinct() for filtering duplicated records in Linq


I have some duplicated email records. I also need to return IQueryable type.

I tried Distinct() but I did not work for me because I want to return IQueryable Type. I got an error that cannot implicitly convert type system collections generic list to System.Linq.IQueryable (Are you missing a cast):

public IQueryable<acadVParent> GetEmailReceiptsId()
{
   return AsQueryable().Where(o => (o.email != null && o.email != ""));
}

So this has duplicated emails in the collection. I would want to exclude the object record that has duplicated email records.


Solution

  • Just group by email and take the first one in each group (remove duplicates), and at the end convert it to Queryable (here I assume the List or Array, ... name is list):

    var result = list.GroupBy(x => x.email).Select(g => g.First()).AsQueryable();