c# - 告诉 LINQ Distinct 要返回哪个项目

标签 c# linq .net-3.5 c#-3.0 ienumerable

我了解如何在 IEnumerable 上执行 Distinct() 并且我必须为更高级的内容创建 IEqualityComparer 但是有没有一种方法可以告诉您返回哪个重复项?

例如,假设您有一个 List<T>

List<MyClass> test = new List<MyClass>();
test.Add(new MyClass {ID = 1, InnerID = 4});
test.Add(new MyClass {ID = 2, InnerID = 4});
test.Add(new MyClass {ID = 3, InnerID = 14});
test.Add(new MyClass {ID = 4, InnerID = 14});

然后你做:

var distinctItems = test.Distinct(new DistinctItemComparer());

class DistinctItemComparer : IEqualityComparer<MyClass> {

    public bool Equals(MyClass x, MyClass y) {
        return x.InnerID  == y.InnerID;;
    }

    public int GetHashCode(MyClassobj) {
        return obj.InnerID.GetHasCode();
    }
}

此代码将返回 ID 为 1 和 3 的类。有没有办法返回 ID 匹配 2 和 4。

最佳答案

我不相信它实际上是保证的,但我会非常惊讶地看到 Distinct 的行为从返回项目中出现的顺序发生变化源序列。

所以,如果您想要特定的项目,您应该以这种方式订购您的源序列。例如:

items.OrderByDescending(x => x.Id)
     .Distinct(new DistinctItemComparer());

请注意,将 Distinct 与自定义比较器一起使用的一种替代方法是使用 MoreLINQ 中的 DistinctBy :

items.OrderByDescending(x => x.Id)
     .DistinctBy(x => x.InnerId);

虽然您不能保证从 Distinct 订购的正常 LINQ to Objects 不会改变,但我很乐意为 MoreLINQ 添加保证 :)(这是唯一的订购老实说,无论如何都是明智的。)

另一种替代方法是改用 GroupBy - 然后对于每个内部 ID,您可以获得 所有 匹配项,然后从那里开始。

关于c# - 告诉 LINQ Distinct 要返回哪个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2545493/

相关文章:

c# - 此代码的 LINQ 方法

c# - 同时播放 2 个声音

c# - ftp 损坏 exe 和 dll 文件 (C#)

c# - 与数据库的 SSL 连接

c# - 带有函数参数的重载函数的奇怪模糊调用

c# - Log4net XMLLayout 产生太多元素

c# - 如何使用 Linq 根据另一个列表过滤列表?

linq - 过滤 Select 中的 Null 值

c# - 如何忽略 REG_EXPAND_SZ 中的环境变量?

wpf - 如何为 WPF WebBrowser 制作动画