简体   繁体   English

忽略字段之一的列表中不同项目的数量

[英]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: 现在,我们有2个Person对象:

  • John Doe 约翰·杜
  • Boring St. 5 无聊的圣5
  • 1 1个

and

  • John Doe 约翰·杜
  • Boring St. 5 无聊的圣5
  • 2 2

These 2 entries in the ListOfPeople are NOT distinct to me. ListOfPeople中的这两个条目对我而言不是ListOfPeople的。 I want to get number of distinct entries in ListOfPeople while ignoring the ID field. 我想在忽略ID字段的同时获取ListOfPeople中不同条目的数量。 If I just do Distinct() it will treat those 2 objects as that (since ID is not the same). 如果我只是执行Distinct()它将把这2个对象视为该对象(因为ID不相同)。

Create an IEqualityComparer<Person> implementation that defines how you want the values to be compared. 创建一个IEqualityComparer<Person>实现,该实现定义如何比较值。 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. 需要注意的是,在那一刻,你没有重载Equals / GetHashCode或实现IEquatable<Person> ,所以即使两个对象的所有属性相同的将被视为不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM