gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:27:47 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com