[英]Get differences between two list
I have a 2 lists of an object type: 我有一个对象类型的2个列表:
List<MyClass> list1;
List<MyClass> list2;
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);
You may use FindAll
to get the result you want, even you don't have IEquatable
or IComparable
implemented in your MyClass
. 您可以使用
FindAll
获得所需的结果,即使您没有在MyClass
实现IEquatable
或IComparable
。 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.