C# remove duplicates from Listlt;Listlt;intgt;gt;(C# 从 Listlt;Listlt;intgt;gt; 中删除重复项)
问题描述
例如,我无法想出最有效的算法来从 List<List<int>>
中删除重复项(我知道这看起来像 int 的列表[]
,但只是出于视觉目的这样做:
I'm having trouble coming up with the most efficient algorithm to remove duplicates from List<List<int>>
, for example (I know this looks like a list of int[]
, but just doing it that way for visual purposes:
my_list[0]= {1, 2, 3};
my_list[1]= {1, 2, 3};
my_list[2]= {9, 10, 11};
my_list[3]= {1, 2, 3};
所以输出就是
new_list[0]= {1, 2, 3};
new_list[1]= {9, 10, 11};
如果您有任何想法,请告诉我.我真的很感激.
Let me know if you have any ideas. I would really appreciate it.
推荐答案
自定义EqualityComparer
:>
public class CusComparer : IEqualityComparer<List<int>>
{
public bool Equals(List<int> x, List<int> y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(List<int> obj)
{
int hashCode = 0;
for (var index = 0; index < obj.Count; index++)
{
hashCode ^= new {Index = index, Item = obj[index]}.GetHashCode();
}
return hashCode;
}
}
然后您可以通过使用 Distinct 和自定义比较器来获得结果方法:
Then you can get the result by using Distinct with custom comparer method:
var result = my_list.Distinct(new CusComparer());
将索引包含在方法GetHashCode
中以确保不同的顺序不相等
Include the index into method GetHashCode
to make sure different orders will not be equal
这篇关于C# 从 List<List<int>> 中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 从 List<List<int>> 中删除重


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04