且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在列表中删除重复的对象(C#)

更新时间:2023-02-13 22:18:55

您需要使用鲜明接受一个 的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 属性是(和它听起来像它可能是,因为这是最有可能在字符串)。你应该做的,并返回 0 的GetHashCode 如果 MetricText 。在另一方面,如果 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());