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?

allencoded
  • 7,015
  • 17
  • 72
  • 126
  • 2
    Your code doesn't compile. What format do you get? What format do you want? – Blorgbeard Sep 28 '15 at 19:25
  • Unless I'm missing something this is standard case of [C# distinct does not work](https://www.bing.com/search?q=c%23+distinct+does+not+work) - covered in many SO questions - i.e. http://stackoverflow.com/questions/1365748/distinct-not-working-with-linq-to-objects. If not the case please clarify the post so it can be re-opened. – Alexei Levenkov Sep 28 '15 at 19:29
  • To convert IEnumerable to List, use ToList(). 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? – Harald Coppoolse Sep 29 '15 at 07:29

1 Answers1

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();
Matt Whetton
  • 6,616
  • 5
  • 36
  • 57