Comparing two string arrays in C#

68,554

Solution 1

You can use Linq:

bool areEqual = a.SequenceEqual(b);

Solution 2

Try using Enumerable.SequenceEqual:

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

Solution 3

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

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)

Share:
68,554
Wes Field
Author by

Wes Field

Updated on July 08, 2022

Comments

  • Wes Field
    Wes Field almost 2 years

    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.