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:
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With