gpt4 book ai didi

C# 从 List> 中删除重复项

转载 作者:可可西里 更新时间:2023-11-01 07:50:10 25 4
gpt4 key购买 nike

我无法想出最有效的算法来从 List<List<int>> 中删除重复项,例如(我知道这看起来像 int[] 的列表,但只是出于视觉目的这样做:

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};

如果您有任何想法,请告诉我。我真的很感激。

最佳答案

构建自定义 EqualityComparer<List<int>> :

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得到结果使用自定义比较器方法:

var result = my_list.Distinct(new CusComparer());

编辑:

将索引包含到方法中 GetHashCode确保不同的订单不会相等

关于C# 从 List<List<int>> 中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com