【问题标题】:How does Distinct() work?Distinct() 是如何工作的?
【发布时间】:2013-03-15 02:18:04
【问题描述】:

假设我有这个:

class Foo
{
    public Guid id;
    public string description;
}

var list = new List<Foo>();
list.Add(new Foo() { id = Guid.Empty, description = "empty" });
list.Add(new Foo() { id = Guid.Empty, description = "empty" });
list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty" });
list.Add(new Foo() { id = Guid.NewGuid(), description = "notempty2" });

现在,当我这样做时:

list = list.Distinct().Tolist();

它显然返回 4 个元素。我想要一个方法,它比较我在类中的所有数据,并返回唯一元素,检查类的每个属性。我是否需要编写自己的比较器,或者是否有内置的东西可以这样工作?

【问题讨论】:

  • 你必须编写自己的比较器,或者实现IEquatable

标签: c# .net linq distinct


【解决方案1】:

您必须覆盖 Foo.Equals(以及随后的 Foo.GetHashCode)才能显式比较每个字段。否则它将使用默认实现,Object.Equals (ReferenceEquals)。

或者,您可以将IEqualityComparer 显式传递给Distinct() 方法。


请注意,虽然使用 匿名类 确实会返回 3 个元素。根据您想在哪里使用 Foo 以及您需要多少编译时类型安全性,您可以这样做:

var list = new List<dynamic>();
list.Add(new { id = Guid.Empty, description = "empty" });
list.Add(new { id = Guid.Empty, description = "empty" });
list.Add(new { id = Guid.NewGuid(), description = "notempty" });
list.Add(new { id = Guid.NewGuid(), description = "notempty2" });

list = list.Distinct().ToList(); //3 elements selected

【讨论】:

  • 我建议走IEqualityComparer 路线。以这种方式将一个类扩展为在不同的上下文中“相等”比重写 Equals 方法要容易得多。
【解决方案2】:

它使用EqualityComparer.Default比较每两个项目,直到specifiedIEqualityComparer的另一个实现

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多