獲取

2012-05-01 46 views
2

我有一個對象類型的2只列出兩個列表之間的差異:
獲取

 
List<MyClass> list1;
List<MyClass> list2;

什麼是提取這兩個表之間的數據差異的最佳方法(性能和乾淨的代碼)?
我的意思是獲取添加,刪除或更改的對象(以及更改)?

+2

HTTP: //msdn.microsoft.com/en-us/library/bb460136.aspx,http://msdn.microsoft.com/en-us/library/bb300779.aspx,http://msdn.microsoft.com/en- us/library/bb397894.aspx –

+7

「改變」是什麼意思?例如,如果list1具有「foO」並且list2具有「bar」,那麼是添加和刪除還是更改? –

+4

請給予預期的輸入和輸出。你的問題並沒有說明你是關心對象發生的順序,還是你可以在同一個列表中有重複的對象,或者你如何確定兩個對象是否代表同一個對象,即使它們被「改變」。 – StriplingWarrior

回答

12

嘗試ExceptUnion,但是您需要爲兩者都找到差異。

var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList(); 

或作爲LINQ的替代方案,有可能是一個更快的方法:HashSet.SymmetricExceptWith():

var exceptions = new HashSet(list1); 

exceptions.SymmetricExceptWith(list2); 
+0

+1爲未充分利用的'HashSet'。 –

0

您可以使用FindAll得到您想要的結果,即使您沒有在您中實施IEquatableIComparable r MyClass。這裏有一個例子:

List<MyClass> interetedList = list1.FindAll(delegate(MyClass item1) { 
    MyClass found = list2.Find(delegate(MyClass item2) { 
    return item2.propertyA == item1.propertyA ...; 
    } 
    return found != null; 
}); 

以同樣的方式,你可以從list2通過比較list1讓你感興趣的項目。

此策略也可能會得到您的「更改」項目。

0

一個辦法讓那些無論是在列表1或列表2,但不是在這兩個項目是:

var common = list1.Intersect(list2); 
var exceptions = list1.Except(common).Concat(list2.Except(common)); 
0

嘗試此對象的比較和循環它周圍的List<T>

public static void GetPropertyChanges<T>(this T oldObj, T newObj) 
{ 
    Type type = typeof(T); 
    foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) 
    { 
     object selfValue = type.GetProperty(pi.Name).GetValue(oldObj, null); 
     object toValue = type.GetProperty(pi.Name).GetValue(newObj, null); 
     if (selfValue != null && toValue != null) 
     { 
      if (selfValue.ToString() != toValue.ToString()) 
      { 
      //do your code 
      } 
     } 
    } 
}