Find difference between two lists in C#
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 2, 4, 6, 8 }; var diff = first.Except(second); Console.WriteLine(String.Join(", ", diff)); // 1, 3, 5 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 2, 4, 6, 8 }; var diff = first.Except(second).Concat(second.Except(first)); Console.WriteLine(String.Join(", ", diff)); // 1, 3, 5, 6, 8 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { var first = new List<int> { 1, 2, 3, 4, 5 }; var second = new List<int> { 2, 4, 6, 8 }; var firstSet = first.ToHashSet(); firstSet.SymmetricExceptWith(second); var diff = firstSet.ToList(); Console.WriteLine(String.Join(", ", diff)); // 1, 3, 5, 6, 8 } } |
That’s all about finding the difference between two lists in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)