Question

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?

Was it helpful?

Solution

I think this the shortest way to solve this

foreach (string com in com2 )
{
    if (!com1.Contains(com))
    {
        MessageBox.Show(com);
    }
}

OTHER TIPS

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.

Using the Linq Except extension:

IEnumerable<string> result = com2.Except(com1); 
// result: { "COM8" }

You could use IEnumerable.Except.

If you want everything that's in one list but not both, in a single expression, you could use Union, Intersect and Except:

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

As others have already said, the Except extension method is definitely the way to go here. I will add, however, that it looks like you might want some control over how the comparisons are made; if 'COM8' refers to a serial port identifier, then you'd want to perform a case-insensitive comparison:

var result = com2.Except(com1, StringComparer.OrdinalIgnoreCase);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top