【发布时间】:2016-10-26 14:46:21
【问题描述】:
我正在尝试比较(属性的值)列表中的类型实例并消除重复项。 根据 MSDN,GetHashCode() 是比较两个对象的方法之一。
哈希码用于高效插入和查找 基于哈希表的集合。哈希码不是 永久价值
考虑到这一点,我开始编写我的扩展方法,如下所示
public static class Linq
{
public static IEnumerable<T> DistinctObjects<T>(this IEnumerable<T> source)
{
List<T> newList = new List<T>();
foreach (var item in source)
{
if(newList.All(x => x.GetHashCode() != item.GetHashCode()))
newList.Add(item);
}
return newList;
}
}
尽管对象的数据相同,但这个条件总是给我false。
newList.All(x => x.GetHashCode() != item.GetHashCode())
最后我想像这样使用它
MyDuplicateList.DistinctObjects().ToList();
如果比较对象的所有字段太多,我可以这样使用,
MyDuplicateList.DistinctObjects(x=>x.Id, x.Name).ToList();
这里我说的是只比较这些对象的这两个字段。
【问题讨论】:
-
有一个内置的 LINQ 函数,
Distinct(),它接受一个表达式来确定唯一性。这不是你想要的吗? -
首先 - 如果 GetHashCode 相等,并不意味着对象相等,反之亦然
-
@GEEF .Distinct() 没有做这项工作。
-
@YacoubMassad GetHashCode() 绝对是由任何 T 实现的,考虑到它基于 C#
object。 -
它没有做这项工作,因为您需要使用比较器或为对象实现接口 IEquatable
,覆盖 equals 和 gethashcode 否则它正在比较引用