删除列表中的重复对象(C#) [英] Removing duplicate objects in a list (C#)

查看:477
本文介绍了删除列表中的重复对象(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我了解如何通过使用Linq的 Distinct()来解决列表中重复的问题。但是,如何根据对象的特定属性删除重复项?

So I understand how to remove duplicates in a list when it comes to strings and int, etc by using Distinct() from Linq. But how do you remove duplicates based on a specific attribute of an object?

例如,我有一个 TimeMetric 类。这个 TimeMetric 类有两个属性: MetricText MetricTime 。我有一个名为 TimeMetrics 的列表,名为 MetricList 。我想删除任何重复的 TimeMetric 与相同的 MetricText 属性。 TimeMetric 值可以相同,但如果任何 TimeMetric 具有相同的 MetricText ,它必须是未重复的。

For example, I have a TimeMetric class. This TimeMetric class has two attributes: MetricText and MetricTime. I have a list of TimeMetrics called MetricList. I want to remove any duplicates TimeMetric with the same MetricText attribute. The TimeMetric value can be the same but if any TimeMetric has the same MetricText, it must be unduplicated.

推荐答案

您需要使用 需要一个 IEqualityComparer< TimeMetric> ; 实例作为第二个参数。定义一个比较器:

You need to use the second overload of Distinct that takes an IEqualityComparer<TimeMetric> instance as a second parameter. Define a comparer like this:

class MyComparer : IEqualityComparer<TimeMetric>
{
    public bool Equals(TimeMetric x, TimeMetric y)
    {
        return x.MetricText.Equals(y.MetricText);
    }

    public int GetHashCode(TimeMetric obj)
    {
        return obj.MetricText.GetHashCode();
    }
}

重要提示:以上代码不检查 MetricText 属性是 null (这听起来可能是,因为它最可能是一个字符串)。你应该这样做,并从 GetHashCode 如果 MetricText 返回 0 null 。另一方面,如果 MetricText 的类型是值类型,则不需要执行任何修改。

Important note: The above code does not check for the case where the MetricText property is null (and it sounds like it could be, since it's most probably a string). You should do that and return 0 from GetHashCode if MetricText is null. On the other hand, if the type of MetricText is a value type, you don't need to perform any modification.

然后:

var list = new List<TimeMetric> { ... };
var unique = list.Distinct(new MyComparer());

这篇关于删除列表中的重复对象(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆