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.

1

3 Answers 3

9

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?

Sign up to request clarification or add additional context in comments.

5 Comments

The type argument for method yadda yadda cannot be inferred from the usage. Try specifying the type arguments explicitly.
@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?
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.
@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 stackoverflow.com/questions/4472369/…
@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.
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.

Comments

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

2 Comments

If you implement it in the objects being compared, that would be IEquatable, not IEqualityComparer...
It is actually a List of SelectListItem's

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.