0

I am trying to figure out how to select distinct values from one list and then transpose those distinct values to another list.

I have this:

Model:

public class Participant
{
    public int UserId { get; set; }
    public string Name { get; set; }
}

Controller Code:

List<Participant> participants = new List<Participant>();
participants = project
    .QuickView
    .Select(x => new Participant { x.UserId, x.FullName})
    .Distinct()
    .ToList();

That seems to get me the distinct values UserId and FullName but not in the List format I need. I get an IEnumerable format not List format. What am I missing to get the LINQ to place the the results in a new Participant List?

3
  • 2
    Your code doesn't compile. What format do you get? What format do you want? Commented Sep 28, 2015 at 19:25
  • Unless I'm missing something this is standard case of C# distinct does not work - covered in many SO questions - i.e. stackoverflow.com/questions/1365748/…. If not the case please clarify the post so it can be re-opened. Commented Sep 28, 2015 at 19:29
  • To convert IEnumerable<T> to List<T>, use ToList<T>(). Also: in order for the Distinct() to work as you want, make sure that you fully implement equality the way you want it: are two Participants equal if they are the same object, or if the values of the objects are equal, or is the user Id unique and are two Participants equal if they have the same userId? Commented Sep 29, 2015 at 7:29

1 Answer 1

1

You dont really want to be using the select. Instead use a custom IEqualityComparer with the Distinct method. Something like this

public class CustomEqualityComparer : IEqualityComparer<Participant>
{
    public bool Equals(Participant x, Participant y)
    {
        return x.UserId == y.UserId && x.Name == y.Name;
    }

    public int GetHashCode(Participant obj)
    {
        return new Tuple<int, string>(obj.UserId, obj.Name).GetHashCode();
    }
}

Then your call would look like this:

participants = project.QuickView.Distinct(new CustomEqualityComparer()).ToList();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.