-1

I have a MyUser object defined in my code with several properties...

public class MyUser
{
    public Guid UserId;
    public string EmailAddress;
    public string UserName;
}

Then I have a List of these MyUser objects....

List<MyUser> userList

How do I get rid of all duplicates based on only ONE PROPERTY of each myObject, such as UserName?

So basically if I have a List of 100 of these MyUser objects, I only want ONE occurrence of each UserName. So, if the UserName shows up more than once, remove the duplicates and keep only one object per UserName. In the end, I'll have a list that only has unique usernames (along with the other properties).

I thought I could do it with LINQ Distinct, but Distinct doesn't allow me to tell it to only consider ONE property.

WebDevGuy2
  • 1,159
  • 1
  • 19
  • 40

1 Answers1

0

GroupBy the UserId and then take the first of each group:

List<MyUser> result = userList.GroupBy(x => x.UserId)
                              .Select(x => x.First())
                              .ToList();
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126