获得两个列表之间的差异

我有一个对象类型的2个列表:

 List  list1; 
List list2;

提取这两个List之间数据差异的最佳方法(性能和干净代码)是什么?
我的意思是获取添加,删除或更改的对象(以及更改)?

尝试使用Union Except ,但您需要为两者执行此操作才能找到两者的差异。

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

或者作为Linq替代方案,可能有更快的方法:HashSet.SymmetricExceptWith():

 var exceptions = new HashSet(list1); exceptions.SymmetricExceptWith(list2); 
 IEnumerable differenceQuery = list1.Except(list2); 

http://msdn.microsoft.com/en-us/library/bb397894.aspx

即使您没有在MyClass实现IEquatableIComparable ,也可以使用FindAll获得所需的结果。 这是一个例子:

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

以同样的方式,您可以通过与list1比较从list2获取您感兴趣的项目。

此策略也可能会获得“更改”的项目。

获取list1或list2中但不包含在两者中的项的一种方法是:

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

尝试使用它进行对象比较,并为List循环它

 public static void GetPropertyChanges(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 } } } }