获取两个列表之间的差异

本文关键字:之间 列表 两个 获取 | 更新日期: 2023-09-27 18:32:52

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

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

获取两个列表之间的差异

尝试使用

Union Except ,但您需要对两者执行此操作才能找到两者的差异。

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

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

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

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

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

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

此策略也可能使您的"更改"项目。

获取列表 1 或列表 2 中但不在两者中的项的一种方法是:

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

尝试这样做进行对象比较,并围绕它循环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
            }
        }
    }
}