不同的列表列表,其中列表包含相同的值,但顺序不同 [英] Distinct list of lists, where lists contains same values but in different order

查看:103
本文介绍了不同的列表列表,其中列表包含相同的值,但顺序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单:

var list = new List<List<int>>();

可能包含的

list[0] = {1, 2, 3, 4}
list[1] = {3, 1, 2, 4}
list[2] = {2, 1, 7, 3}

如何检测[0]和[1]之间的重复项并删除其中之一?代码是锐利的.

How can I detect the duplicate between [0] and [1] and remove one of them? Code is c-sharp.

实际上这不是int,但这不应改变问题.

In reality it's not a int, but that shouldn't change the question.

推荐答案

您可以编写自己的IEqualityComparer<List<int>>实现.对于GetHashCode(),它将仅返回列表中元素的所有哈希码的XOR.对于Equals(),它将从第一个列表中创建一个新的HashSet<int>,并调用 HashSet<T>.SetEquals 在其上,传入第二个列表.请注意,这是假设没有重复的元素. (否则{1,1,2}将等于{1,2,2},但是具有不同的哈希码.)

You could write your own implementation of IEqualityComparer<List<int>>. For GetHashCode() it would simply return the XOR of all the hash codes of the elements in the list. For Equals() it would create a new HashSet<int> from the first list, and call HashSet<T>.SetEquals on it, passing in the second list. This assumes there will be no duplicate elements, mind you. (Otherwise { 1, 1, 2 } will be equal to { 1, 2, 2 } but have a different hash code.)

一旦您达到目标,就可以使用Distinct:

Once you've got that far, you can use Distinct:

var distinct = list.Distinct(new CustomEqualityComparer());

作为一种替代方法,您可以使用HashSet<T>作为您的收藏类型吗?然后真的简单:

As an alternative approach, could you use HashSet<T> as your collection type to start with? Then it's really easy:

var distinct = sets.Distinct(HashSet<int>.CreateSetComparer());

如果需要列表作为输入,但可以处理集合作为输出:

If you need lists as the input but can cope with sets as the output:

var distinct = list.Select(x => new HashSet<int>(x))
                   .Distinct(HashSet<int>.CreateSetComparer());

这篇关于不同的列表列表,其中列表包含相同的值,但顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆