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

前端 未结 4 1170
傲寒
傲寒 2020-12-19 06:49

I got a list:

var list = new List>();

which could contain

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


        
4条回答
  •  生来不讨喜
    2020-12-19 07:20

    You could write your own implementation of IEqualityComparer>. 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 from the first list, and call HashSet.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 as your collection type to start with? Then it's really easy:

    var distinct = sets.Distinct(HashSet.CreateSetComparer());
    

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

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

提交回复
热议问题