Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the "diff" between two arrays in C#?

Tags:

arrays

c#

Let's say I have these two arrays:

var array1 = new[] {"A", "B", "C"}; var array2 = new[] {"A", "C", "D"}; 

I would like to get the differences between the two. I know I could write this in just a few lines of code, but I want to make sure I'm not missing a built in language feature or a LINQ extension method.

Ideally, I would end up with the following three results:

  • Items not in array1, but are in array2 ("D")
  • Items not in array2, but are in array1 ("B")
  • Items that are in both

Thanks in advance!

like image 652
Michael Avatar asked Mar 25 '09 20:03

Michael


People also ask

How do you find the difference between elements in arrays?

You can use array#map . For the first index value subtract from 0 and for other indexes, subtract from the previous number.

How do you find the difference between two arrays in TypeScript?

To get the difference between two arrays in TypeScript: Use the filter() method to iterate over the first array. Check if each element is not contained in the second array. Repeat the steps, but this time iterate over the second array.


1 Answers

If you've got LINQ available to you, you can use Except and Distinct. The sets you asked for in the question are respectively:

- array2.Except(array1) - array1.Except(array2) - array1.Intersect(array2) 
like image 143
Jon Skeet Avatar answered Sep 28 '22 21:09

Jon Skeet