Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get differences between two list

Tags:

c#

.net

object

I have a 2 lists of an object type:

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

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)?
like image 830
Mehrdad Avatar asked Jul 29 '26 17:07

Mehrdad


1 Answers

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

OR as a Linq alternative, there could be a much faster approach: HashSet.SymmetricExceptWith():

var exceptions = new HashSet(list1);

exceptions.SymmetricExceptWith(list2);
like image 148
mattytommo Avatar answered Aug 01 '26 07:08

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!