Comparing two collections for equality irrespective of the order of items in them

后端 未结 19 1920
我在风中等你
我在风中等你 2020-11-22 10:28

I would like to compare two collections (in C#), but I\'m not sure of the best way to implement this efficiently.

I\'ve read the other thread about Enumerable.Sequen

19条回答
  •  抹茶落季
    2020-11-22 11:10

    In the case of no repeats and no order, the following EqualityComparer can be used to allow collections as dictionary keys:

    public class SetComparer : IEqualityComparer> 
    where T:IComparable
    {
        public bool Equals(IEnumerable first, IEnumerable second)
        {
            if (first == second)
                return true;
            if ((first == null) || (second == null))
                return false;
            return first.ToHashSet().SetEquals(second);
        }
    
        public int GetHashCode(IEnumerable enumerable)
        {
            int hash = 17;
    
            foreach (T val in enumerable.OrderBy(x => x))
                hash = hash * 23 + val.GetHashCode();
    
            return hash;
        }
    }
    

    Here is the ToHashSet() implementation I used. The hash code algorithm comes from Effective Java (by way of Jon Skeet).

提交回复
热议问题