简体   繁体   English

获得两个列表之间的差异

[英]Get differences between two list

I have a 2 lists of an object type: 我有一个对象类型的2个列表:

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

What is the best way (performance and clean code) to extract differences in data between these two List? 提取这两个List之间数据差异的最佳方法(性能和干净代码)是什么?
I mean get objects that is added, deleted, or changed (and the change)? 我的意思是获取添加,删除或更改的对象(以及更改)?

Try Except with Union , but you'll need to do it for both in order to find differences in both. 尝试使用Union Except ,但您需要为两者执行此操作才能找到两者的差异。

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

OR as a Linq alternative, there could be a much faster approach: HashSet.SymmetricExceptWith(): 或者作为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

You may use FindAll to get the result you want, even you don't have IEquatable or IComparable implemented in your MyClass . 您可以使用FindAll获得所需的结果,即使您没有在MyClass实现IEquatableIComparable Here is one example: 这是一个例子:

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

In the same way, you can get your interested items from list2 by comparing to list1 . 以同样的方式,您可以通过与list1比较从list2获取您感兴趣的项目。

This strategy may get your "changed" items as well. 此策略也可能会获得“更改”的项目。

One way to get items that are either in list1 or in list2 but not in both would be: 获取list1或list2中但不包含在两者中的项的一种方法是:

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

Try this for objects comparison and loop around it for List<T> 尝试使用它进行对象比较,并为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
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM