3

Here is how I am attempting to get a distinct List of items...

    var queryResults = PatientList.Distinct();
    PatientList = queryResults.ToList<SelectListItem>();

For some reason, I am not getting a distinct list here.

dlev
  • 48,024
  • 5
  • 125
  • 132
SoftwareSavant
  • 9,467
  • 27
  • 121
  • 195
  • possible duplicate of [Distinct not working with LINQ to Objects](http://stackoverflow.com/questions/1365748/distinct-not-working-with-linq-to-objects) – dlev Aug 31 '11 at 12:53

3 Answers3

8

Use

var queryResults = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault())
    PatientList = queryResults.ToList<SelectListItem>();

You can always try

 PatientList = PatientList.GroupBy(x=>x.Id).Select(x=>x.FirstOrDefault()).ToList<SelectListItem>();

It will give you the distinct results based off whatever you group by

Check out http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx

Also another question for reference: Returning a Distinct IQueryable with LINQ?

Community
  • 1
  • 1
Gage
  • 7,365
  • 9
  • 47
  • 77
  • The type argument for method yadda yadda cannot be inferred from the usage. Try specifying the type arguments explicitly. – SoftwareSavant Aug 31 '11 at 13:06
  • @DmainEvent, Change x.Id to whatever you need to group everything by. Not sure what you mean by your comment, which argument cannot be inferred? – Gage Aug 31 '11 at 13:14
  • sorry about that. I am working on a different computer right now to right this message than the one that has the code (Little lazy this morning :-) ). But I did change it to the right value... Not sure why it isn't working. – SoftwareSavant Aug 31 '11 at 13:18
  • @DainEvent, hmm Ok well which line did you get that error on? The groupby or where your converting to a list? The groupby should work correct what are you grouping everything by? What you are doing is similar to http://stackoverflow.com/questions/4472369/returning-a-distinct-iqueryable-with-linq – Gage Aug 31 '11 at 13:41
  • @Gage... I was doing my usual and being an idiot. I forgot to put () at the end of FirstOrDefault. It works now. Thanks a ton. – SoftwareSavant Aug 31 '11 at 14:30
1

Not sure what kind of items your PatientList contains, but I guess you have to implement IEquatable on your custom object.

This have been aswered before here: Distinct not working with LINQ to Objects

Community
  • 1
  • 1
Muttok
  • 671
  • 6
  • 4
1

Your SelectListItem class needs to override Equals and GetHashCode (and optionally implement IEquatable<SelectListItem>). Otherwise, different instances with the same values will be considered different.

Another option is to implement a IEqualityComparer<SelectListItem> and pass it as the second parameter to Distinct.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758