2011-04-26 53 views
0

我有以下情況:比較自定義對象c#

我有一個可以循環任意次數的循環。在那個循環中,我調用了一個返回List<CustomClass>的方法。在完成循環之後,我需要能夠比較每個列表中的所有List<CustomClass>項目,並查看哪些項目在所有項目之間是共同的。爲了做到這一點,我試圖把所有List<CustomClass>放入另一個列表:List<List<CustomClass>,然後我需要使用所有這些來查看所有這些列表中存在哪些。我會在我的CustomClass(字符串名稱)

的一個屬性進行比較,這是我迄今爲止

public class CustomClass 
{ 
    public string name; 
} 

public List<CustomClass> SomeMethod() 
{ 
    List<List<CustomClass>> bigList = new List<List<CustomClass>>(); 
    List<CustomClass> finalList = new List<CustomClass>(); 
    for (int i=0;i<=5;i++) 
    {    
     List<List<CustomClass>> newList = GetNewList(); 
     bigList.Add(newList); 
    } 
    //I now need to compare everything in bigList and create a new list with all common 
    //items in the list of bigList. 
    return finalList ; 
} 

public List<CustomClass> GetNewList() 
{ 
    List<CustomClass> newList = new List<CustomClass>(); 
    for (int i=0;i<=5;i++) 
    {    
     CustomClass newClass = new CustomClass(); 
     newClass.name = "some name"; 
     newList.Add(newClass); 
    } 
    return newList; 
{ 

我希望這是有道理的。任何幫助,這是非常感謝。

感謝

編輯

例如在List<List<CustomClass>>每個List<CustomClass>包含名稱CustomClass設置爲「皮特」,然後,我想創建一個CustomClass與名稱設置爲「皮特」,並將其添加到最後的名單。

+0

請bigList列表定義*常用物品*自定義比較。 – 2011-04-26 08:53:58

+0

請參閱編輯。謝謝 – Peuge 2011-04-26 09:06:43

回答

4

看看哪些個個之間有共同

使用Intersect擴展方法:

var common = list1.Intersect(list2); 

注意,對於這個工作,你應該:

  • 覆蓋EqualsGetHashCodeCustomClass
  • 使CustomClass實施IEquatable<CustomClass>
  • 提供Intersect與實現IEqualityComparer<CustomClass>
+0

謝謝你,讓我走上正確的道路。這個人可疑地問了一個比我更好的方式:) http://stackoverflow.com/questions/1674742/intersection-of-multiple-lists-with-ienumerable-intersect – Peuge 2011-04-26 09:21:04