簡體   English   中英

System.Collections.Generic.List <T>的等於方法......?

[英]Equals method of System.Collections.Generic.List<T>…?

我正在創建一個派生自List的類...

public class MyList : List<MyListItem> {}

我已經覆蓋了MyListItem的Equals ...

public override bool Equals(object obj)
{
    MyListItem li = obj as MyListItem;
    return (ID == li.ID);  // ID is a property of MyListItem
}

我想在MyList對象中也有一個Equals方法,它將比較列表中的每個項目,在每個MyListItem對象上調用Equals()。

簡單地打電話會很好...

MyList l1 = new MyList() { new MyListItem(1), new MyListItem(2) };
MyList l2 = new MyList() { new MyListItem(1), new MyListItem(2) };

if (l1 == l2)
{
    ...
}

...並按值完成列表的比較。

什么是最好的方式......?

您可以在列表中使用SequenceEqual linq方法,因為您的列表實現了IEnumerable。 這將驗證所有元素是否相同且順序相同。 如果訂單可能不同,您可以先對列表進行排序。

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM