Number of distinct items in a List with ignoring one of the fields

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:

  • John Doe
  • Boring St. 5
  • 1

and

  • John Doe
  • Boring St. 5
  • 2

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).

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow