Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

c# - Distinct list of lists, where lists contains same values but in different order

I got a list:

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

which could contain

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)

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

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

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...