在列表中删除重复的对象(C#) [英] Removing duplicate objects in a list (C#)
问题描述
所以我知道如何删除重复列表中时,它通过使用鲜明的()
从LINQ的涉及到字符串和INT等。但你如何删除基于对象的特定属性复制?
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
属性是空
(和它听起来像它可能是,因为这是最有可能在字符串
)。你应该做的,并返回 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());
这篇关于在列表中删除重复的对象(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!