Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the differences between two string arrays in C#?

Tags:

arrays

c#

.net

linq

How to compare two array string using C#.net? Eg:

string[] com1 = { "COM6", "COM7" };
string[] com2 = { "COM6", "COM7","COM8" };

Here com1 and com2 are Array string. Result: COM8. How to achieve this?


2 Answers

Sounds like you want everything in array2 except what's in array1:

var onlyInArray2 = array2.Except(array1);

Of course, if you also wanted to know what was only in array1 you could use:

var onlyInArray1 = array1.Except(array2);

(This all requires .NET 3.5 or higher, or an alternative LINQ to Objects implementation such as LINQBridge.)

I'm assuming that order isn't important when computing differences - Except is a set-based operator, so assumes that you're regarding the collections as sets.

Note that Except just returns an IEnumerable<T> - if you want the results as arrays, you'll need to call ToArray:

var onlyInArray2 = array2.Except(array1).ToArray();
var onlyInArray1 = array1.Except(array2).ToArray();

If you want the symmetric difference, i.e. you only care about which values are in a single array, rather than which array they came from, you could use:

var onlyInOneArray = array1.Union(array2).Except(array1.Intersect(array2));

or you could use HashSet directly:

var set = new HashSet<string>(array1);
// This modifies the set...
set.SymmetricExceptWith(array2);

In all of these, the resulting order is undefined, although in practice Except will preserve the original order of the first argument. While this is strictly speaking an implementation detail, I think it's very unlikely to change.

Like the other set-based operators in LINQ, Except will only return any element once - so if COM8 appeared twice in array2, it would only appear once in the result.

like image 145
Jon Skeet Avatar answered Sep 14 '25 03:09

Jon Skeet


Using the Linq Except extension:

IEnumerable<string> result = com2.Except(com1); 
// result: { "COM8" }
like image 45
McGarnagle Avatar answered Sep 14 '25 03:09

McGarnagle