Removing duplicate objects in a list (C#)(删除列表中的重复对象 (C#))
问题描述
所以我了解如何使用 Linq 中的 Distinct() 删除列表中的字符串和 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.我有一个名为 MetricList 的 TimeMetrics 列表.我想删除具有相同 MetricText 属性的所有重复项 TimeMetric.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.
推荐答案
您需要使用 Distinct 的第二个重载,它采用 IEqualityComparer 实例作为第二个参数.像这样定义一个比较器:
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 的情况(听起来可能是, 因为它很可能是一个 string).如果 MetricText 为 null,您应该这样做并从 GetHashCode 返回 0.另一方面,如果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#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:删除列表中的重复对象 (C#)
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
