Comparing two string arrays in C#

C#.NetStringLinqEquality

C# Problem Overview


Say we have 5 string arrays as such:

string[] a = {"The","Big", "Ant"};
string[] b = {"Big","Ant","Ran"};
string[] c = {"The","Big","Ant"};
string[] d = {"No","Ants","Here"};
string[] e = {"The", "Big", "Ant", "Ran", "Too", "Far"};

Is there a method to compare these strings to each other without looping through them in C# such that only a and c would yield the boolean true? In other words, all elements must be equal and the array must be the same size? Again, without using a loop if possible.

C# Solutions


Solution 1 - C#

You can use Linq:

bool areEqual = a.SequenceEqual(b);

Solution 2 - C#

Try using Enumerable.SequenceEqual:

var equal = Enumerable.SequenceEqual(a, b);

Solution 3 - C#

if you want to get array data that differ from another array you can try .Except

string[] array1 = { "aa", "bb", "cc" };
string[] array2 = { "aa" };

string[] DifferArray = array1.Except(array2).ToArray();

Output: {"bb","cc"}

Solution 4 - C#

If you want to compare them all in one go:

string[] a = { "The", "Big", "Ant" };
string[] b = { "Big", "Ant", "Ran" };
string[] c = { "The", "Big", "Ant" };
string[] d = { "No", "Ants", "Here" };
string[] e = { "The", "Big", "Ant", "Ran", "Too", "Far" };

// Add the strings to an IEnumerable (just used List<T> here)
var strings = new List<string[]> { a, b, c, d, e };

// Find all string arrays which match the sequence in a list of string arrays
// that doesn't contain the original string array (by ref)
var eq = strings.Where(toCheck => 
                            strings.Where(x => x != toCheck)
                            .Any(y => y.SequenceEqual(toCheck))
                      );

Returns both matches (you could probably expand this to exclude items which already matched I suppose)

Solution 5 - C#

        if (a.Length == d.Length)
        {
            var result = a.Except(d).ToArray();
            if (result.Count() == 0)
            {
                Console.WriteLine("OK");
            }
            else
            {
                Console.WriteLine("NO");
            }
        }
        else
        {
            Console.WriteLine("NO");
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWes FieldView Question on Stackoverflow
Solution 1 - C#Ahmed KRAIEMView Answer on Stackoverflow
Solution 2 - C#DarrenView Answer on Stackoverflow
Solution 3 - C#Manish VadherView Answer on Stackoverflow
Solution 4 - C#CharlehView Answer on Stackoverflow
Solution 5 - C#Dejan CievView Answer on Stackoverflow