C# 获取两个列表之间的差异

C# 获取两个列表之间的差异,c#,.net,object,C#,.net,Object,我有两个对象类型列表: List<MyClass> list1; List<MyClass> list2; 清单1 清单2; 提取这两个列表之间数据差异的最佳方法(性能和干净代码)是什么? 我的意思是获取添加、删除或更改(以及更改)的对象?尝试使用Union进行之外的操作,但您需要同时对这两种操作,以便找到两者之间的差异 var exceptions = list1.Except(list2).Union(list2.Except(list1)).ToList(); 或者作为Li

我有两个对象类型列表:
List<MyClass> list1;
List<MyClass> list2; 清单1
清单2;
提取这两个列表之间数据差异的最佳方法(性能和干净代码)是什么?

我的意思是获取添加、删除或更改(以及更改)的对象?

尝试使用
Union
进行
之外的
操作,但您需要同时对这两种操作,以便找到两者之间的差异

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);

您可以使用
FindAll
来获得想要的结果,即使您的
MyClass
中没有实现
IEquatable
IComparable
。以下是一个例子:

List<MyClass> interetedList = list1.FindAll(delegate(MyClass item1) {
   MyClass found = list2.Find(delegate(MyClass item2) {
     return item2.propertyA == item1.propertyA ...;
   }
   return found != null;
});
List interetedList=list1.FindAll(委托(MyClass item1){
MyClass found=list2.Find(委托(MyClass item2){
返回item2.propertyA==item1.propertyA。。。;
}
返回已找到!=null;
});
同样,通过与
list1
进行比较,您可以从
list2
中获取感兴趣的项目


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

获取列表1或列表2中但不同时存在的项目的一种方法是:

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

在对象比较中尝试此方法,并在
List

publicstaticvoid GetPropertyChanges(这个T oldObj,T newObj)
{
类型=类型(T);
foreach(type.GetProperties中的System.Reflection.PropertyInfo pi(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
对象selfValue=type.GetProperty(pi.Name).GetValue(oldObj,null);
objecttovalue=type.GetProperty(pi.Name).GetValue(newObj,null);
if(selfValue!=null&&toValue!=null)
{
if(selfValue.ToString()!=toValue.ToString())
{
//做你的代码
}
}
}
}

,您所说的“更改”到底是什么意思?例如,如果列表1有“foO”,而列表2有“bar”,这是添加和删除,还是更改?请给出预期的输入和输出。您的问题没有明确说明您是否关心对象出现的顺序,或者是否可以在同一列表中有重复的对象,或者如何确定两个对象是否代表同一个对象,即使它们已“更改”。每个人现在都在等待编辑:DAny对象有一个键,根据它我们可以找到“新的或更改的”,它不会给你列表2中的项目:)@MitchWheat-为什么我发布答案的时间很重要?
var common = list1.Intersect(list2);
var exceptions = list1.Except(common).Concat(list2.Except(common));
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
            }
        }
    }
}