public class Person
{
public string Name { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public int ID { get; set; } = 0;
}
public List<Person> ListOfPeople = new List<Person>();
Now let's have 2 Person
objects:
and
These 2 entries in the ListOfPeople
are NOT distinct to me.
I want to get number of distinct entries in ListOfPeople
while ignoring the ID
field. If I just do Distinct()
it will treat those 2 objects as that (since ID is not the same).
Create an IEqualityComparer<Person>
implementation that defines how you want the values to be compared. You can then use
var distinctByNameAndAddress = people.Distinct(comparer).ToList();
Your equality comparer would look something like this:
public sealed class NameAndAddressComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (ReferenceEquals(x, null) || ReferenceEquals(y, null))
{
return false;
}
return x.Name == y.Name && x.Address == y.Address;
}
public int GetHashCode(Person person) =>
ReferenceEquals(person, null) ? 0
: 23 * person.Name.GetHashCode() + person.Address.GetHashCode();
}
Note that at the moment, you don't override Equals
/GetHashCode
or implement IEquatable<Person>
, so even two objects with all properties the same would be seen as distinct.
See more on this question at Stackoverflow