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

前端 未结 4 1151
傲寒
傲寒 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:21

    Here's the euqality comparer Jon Skeet is talking about (his advice regarding working with HashSets to begin with is also spot on, of course):

        public class EnumerableComparer : IEqualityComparer> 
                                              where T : IComparable
        {
            public bool Equals(IEnumerable first, IEnumerable second)
            {
                if (first == second)
                    return true;
                if ((first == null) || (second == null))
                    return false;
    
                return new HashSet(first).SetEquals(second);
            }
    
            public int GetHashCode(IEnumerable enumerable)
            {
                return enumerable.OrderBy(x => x)
                  .Aggregate(17, (current, val) => current*23 + val.GetHashCode());
            }
        }
    

    So you'd do something like:

    list.Distinct(new EnumerableComparer());
    

    If the elements are not guaranteed to be unique - Use the IEqualityComparer I posted here: Comparing two collections for equality irrespective of the order of items in them

    (In previous edits, I mistakingly posted an IEqulityComparer that compares between two lists of lists - could be very useful when dealing with partitions, but that's a different topic)

提交回复
热议问题