Find difference between two arrays in C#
This post will discuss how to find the difference between two arrays in C#.
1. Using Enumerable.Except Method
The Enumerable.Except method returns the set difference of two sequences by using the default or custom equality comparer. It can be used as follows to find all the elements in the array that doesn’t appear in the specified array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr1 = new int[] { 1, 2, 3, 4, 5 }; int[] arr2 = new int[] { 2, 3, 5 }; var diff = arr1.Except(arr2); Console.WriteLine(String.Join(", ", diff)); // 1, 4 } } |
2. Using SymmetricExceptWith() Method
To get elements that are present in either array, but not both, convert either array into a HashSet and invoke the SymmetricExceptWith() method upon it with the other array as its argument.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Collections.Generic; public class Example { public static void Main() { int[] arr1 = new int[] { 1, 2, 3, 4, 5 }; int[] arr2 = new int[] { 2, 3, 5, 6 }; var diff = new HashSet<int>(arr1); diff.SymmetricExceptWith(arr2); Console.WriteLine(String.Join(", ", diff)); // 1, 4, 6 } } |
That’s all about finding the difference between two arrays 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 :)