Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get one unique List<T> from three non-unique List<T>'s

Tags:

c#

.net

linq

I have three lists of User:

ICollection<User> listOne = _somewhere.GetUsers(1);
ICollection<User> listTwo = _somewhere.GetUsers(2);
ICollection<User> listThree = _somewhere.GetUsers(3);

The "unique" identifier to compare on is a string field called "Email".

How do i get a unique list from the three (e.g no dupes).

I've got a unique list from two lists before using Except, but not sure how to do it with three? Do i have to use Except on the first two, then do it again on the result of the first two and the third?

Also, i should mention that the list of User's comes from external Web API calls, and there is no guarantee that each list has a unique list of email addresses.

So it's like i need two steps:

  1. In each list, get rid of dupes
  2. Combine the three unique lists to get one unique list.
like image 397
RPM1984 Avatar asked Jan 31 '26 20:01

RPM1984


2 Answers

You can just union the lists and do a dedupe (using Distinct()) once on the combined list.

var uniqueList = listOne.Union(listTwo)
                        .Union(listThree)
                        .Distinct(new EmailComparer())
                        .ToList();

For the comparer could be as simple as this:

class EmailComparer : IEqualityComparer<User>
{
    public bool Equals(User x, User y)
    {
        return x.Email == y.Email;
    }

    public int GetHashCode(User obj)
    {
        return obj.Email.GetHashCode();
    }
}

Edit:

As pointed out in comments Distinct() is not needed if we apply the custom email comparer to Union():

var emailComparer = new EmailComparer();
var uniqueList = listOne.Union(listTwo, emailComparer)
                        .Union(listThree, emailComparer)
                        .ToList();
like image 104
BrokenGlass Avatar answered Feb 03 '26 10:02

BrokenGlass


If it does not matter which user you pick from the list of users with the same e-mail, you can do this:

var res = listOne.Concat(listTwo).Concat(listThree)
    .GroupBy(u => u.Email)
    .Select(g => g.First());

Again, this assumes that when e-mail addresses are the same, it does not matter which user you'd pick.

like image 29
Sergey Kalinichenko Avatar answered Feb 03 '26 10:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!