Equals method of System.Collections.Generic.List…?

前端 未结 2 902
逝去的感伤
逝去的感伤 2021-01-17 10:23

I\'m creating a class that derives from List...

public class MyList : List {}

I\'ve overridden Eq

相关标签:
2条回答
  • 2021-01-17 10:58
    public class MyList<T> : List<T>
    {
        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
    
            MyList<T> list = obj as MyList<T>;
            if (list == null)
                return false;
    
            if (list.Count != this.Count)
                return false;
    
            bool same = true;
            this.ForEach(thisItem =>
            {
                if (same)
                {
                    same = (null != list.FirstOrDefault(item => item.Equals(thisItem)));
                }
            });
    
            return same;
        }
    }
    
    0 讨论(0)
  • 2021-01-17 11:10

    You can use SequenceEqual linq method on the list since your list implements IEnumerable. This will verify all the elements are the same and in the same order. If the order may be different, you could sort the lists first.

    0 讨论(0)
提交回复
热议问题