c# - Distinct() 如何处理对象列表?

标签 c# linq distinct

var people = new List<Person>
{
    new Person
    {
        Id = 1,
        Name = "Atish"
    },
    new Person
    {
        Id = 2,
        Name = "Dipongkor"
    },
    new Person
    {
        Id = 1,
        Name = "Atish"
    }
};

Console.WriteLine(people.Distinct().Count());

为什么输出是3

为什么不是2

最佳答案

引用类型的默认相等比较器是引用相等,只返回true如果两个对象引用指向相同实例(即通过单个 new 语句创建)。这与值类型不同,值类型测试值是否相等,并返回 true如果他们所有的数据字段都相等(就像你的两个)。更多信息:Equality Comparisons (C# Programming Guide) .

如果你想改变这个行为,那么你需要实现通用的 IEquatable<T> 您的类型上的接口(interface),以便它比较实例的属性是否相等。 Distinct运算符随后会自动选择此实现并产生预期结果。

编辑:这是 IEquatable<Person> 的示例实现对于你的类(class):

public class Person : IEquatable<Person>
{
    public int Id { get; set; }
    public int Name { get; set; }

    public bool Equals(Person other)
    {
        if (other == null)
            return false;

        return Object.ReferenceEquals(this, other) ||
            this.Id == other.Id &&
            this.Name == other.Name;
    }

    public override bool Equals(object obj)
    {
        return this.Equals(obj as Person);
    }

    public override int GetHashCode()
    {
        int hash = this.Id.GetHashCode();
        if (this.Name != null)
            hash ^= this.Name.GetHashCode();
        return hash;
    }
}

来自guidelines覆盖 ==!=运营商(重点添加):

By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

关于c# - Distinct() 如何处理对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17696147/

相关文章:

c# - ASP.NET 错误事件日志源属性的自定义值

c# - 装箱值只是指向存储在托管堆中的值副本的指针吗?

c# - IDictionary 上的 LINQ 操作

Linq 与 sum 相交

Linq To Entities 可选 不同

c# httpclient post force 单包

c# - 已处理的 RoutedEvent 继续冒泡树

.net - 使 NameValueCollection 可供 LINQ 查询访问

php - 如何从 Select Distinct 中排除一个表

sql - 使用 Hibernate 的标准和投影来选择多个不同的列