获取的两个列表差异差异、两个、列表

2023-09-02 02:03:19 作者:╭女人的苦つ

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

I have a 2 lists of an object type:


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

什么是最好的方式(性能和洁净code)来提取这两个表之间的差异数据? 我的意思是获取被添加,删除或更改对象(的变化)?

What is the best way (performance and clean code) to extract differences in data between these two 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.

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

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

var exceptions = new HashSet(list1);

exceptions.SymmetricExceptWith(list2);
 
精彩推荐
图片推荐