This post will discuss how to find the difference between two lists in C#.

1. Using Enumerable.Except() Method

The standard solution is to use the Enumerable.Except() method, which compares two lists and returns all the elements that appear in the first list but not in the second list. A typical invocation for this method would look like:

Download  Run Code

 
If you want the symmetric difference between two lists, you can call the Except() method twice. The following code example returns elements that are present in the first list without the elements in the second list, and elements present in the second list without the elements in the first list.

Download  Run Code

2. Using HashSet<T>.SymmetricExceptWith Method

However, a more efficient way of finding the symmetric difference is using the HashSet<T>.SymmetricExceptWith method. It changes the current HashSet object to contain only elements that are present either in that object or in the specified collection, but not both. To use it with lists, you can convert any of the lists into a HashSet and call the SymmetricExceptWith() method upon the HashSet with the other list as its argument.

Download  Run Code

That’s all about finding the difference between two lists in C#.