2010-03-08 84 views
10

我創建一個從列表派生的類...System.Collections.Generic.List的等效方法<T> ...?

public class MyList : List<MyListItem> {}

我已經覆蓋MyListItem總量等於...

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) 
{ 
    ... 
} 

...並請有值完成的列表比較。

什麼是最好的方法......?

回答

25

由於列表實現了IEnumerable,因此您可以在列表上使用SequenceEqual linq方法。這將驗證所有元素是相同的並且以相同的順序。如果訂單可能不同,可以先列出清單。

0
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; 
    } 
} 
相關問題