Distinct a list with objects by id
You can use GroupBy to achieve that
var ListOfUsers = ListOfAllUsers.GroupBy(x => x.Id)
.Select(g => g.First())
.ToList();
Distinct
has an overload that receives an instance of IEqualityComparer<T>
, which is an object that contains the logic that allows LINQ to know which two objects are equal, and thus one should be eliminated.
You need to implement this (very simple) interface, something like this:
public class UserEqualityComparer : IEqualityComparer<User>
{
public bool Equals(User x, User y)
{
return x.Id == y.Id;
}
public int GetHashCode (User obj)
{
return obj.Id.GetHashCode();
}
}
And then pass an instance of UserEqualityComparer
to Distinct()
:
var ListOfUsers = ListOfAllUsers.Distinct(new UserEqualityComparer()).ToList();