c# - 从通用列表底部删除重复项

标签 c# linq generics

我正在尝试从通用列表底部删除重复项。我的类定义如下

public class Identifier
{
    public string Name { get; set; }
}

我定义了另一个实现 IEqualityComparer 的类来从列表中删除重复项

public class DistinctIdentifierComparer : IEqualityComparer<Identifier>
{
    public bool Equals(Identifier x, Identifier y)
    {
        return x.Name == y.Name;
    }

    public int GetHashCode(Identifier obj)
    {
        return obj.Name.GetHashCode();
    }
}

但是,我正在尝试删除旧项目并保留最新项目。例如,如果我有如下定义的标识符列表

Identifier idn1 = new Identifier { Name = "X" };
Identifier idn2 = new Identifier { Name = "Y" };
Identifier idn3 = new Identifier { Name = "Z" };
Identifier idn4 = new Identifier { Name = "X" };
Identifier idn5 = new Identifier { Name = "P" };
Identifier idn6 = new Identifier { Name = "X" };

List<Identifier> list =  new List<Identifier>();
list.Add(idn1);
list.Add(idn2);
list.Add(idn3);
list.Add(idn4);
list.Add(idn5);
list.Add(idn6);

我已经实现了

var res = list.Distinct(new DistinctIdentifierComparer());

如何通过使用 distinct 来确保我保留了 idn6 并删除了 idn1 和 idn4?

最佳答案

Most LINQ operators are order-preserving :Distinct() 的 API 表示它将获取遇到的每个项目的第一个实例。如果您想要最后一个实例,只需执行以下操作:

var res = list.Reverse().Distinct(new DistinctIdentifierComparer());

另一个可以避免您必须定义显式比较器的选项是:

var res = list.GroupBy(i => i.Name).Select(g => g.Last());

来自 MSDN:

The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source.

关于c# - 从通用列表底部删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12682696/

相关文章:

c# - 在 Unity/C# 中,.Net 的 async/await 是否真的启动了另一个线程?

c# - MVC Owin Cookie 身份验证 - 覆盖 ReturnUrl 生成

c# - 在这个基本的 Contains<>() 扩展方法和 Lambda 表达式方面需要帮助

c# - SelectMany 有什么问题?

c# - 将带有子查询的sql查询转换为linq语句

c# - Moq - 如何设置惰性界面

c# - 有条件的 Linq 外连接

Java:如何编写指定父类(super class)和接口(interface)的强制转换?

generics - Scala 2.10 中的具体泛型

c# - 在基类中使用动态关键字和调用泛型方法导致 StackOverflowException