66

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.

2

5 Answers 5

116

You can use Linq:

bool areEqual = a.SequenceEqual(b);
Sign up to request clarification or add additional context in comments.

4 Comments

@WesField: Note that this method also loops, just because your requirement was "without looping". Of course it's impossible to compare multiple items without looping. Also note that it uses the default comparer by default which works for value types and the .NET types. For custom reference types you need to create a custom IEqualityComparer<T> for SequenceEqual and/or override Equals and GetHashCode.
@TimSchmelter: Yeah, I realize that a loop is being executed behind the scenes, I just wanted something neat and pretty-looking without room for a muck up.
Returns false when two arrays have exactly same values, but in different order.
"Without looping" is handy when you need to construct an Expression<Func<TIn,TOut>>. This is what I ended up doing for Mock.Is<T> from the Moq library.
25

Try using Enumerable.SequenceEqual:

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

3 Comments

Also a good answer. Could you explain the differences between this and the Linq a.SequenceEqual(b)?
Same thing - ones using the extension method syntax, the other is using the extension method explicitly. Look at extension method sig for details msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
@WesField: There's no difference. An extension method is just a static method in a static class. So you can treat it as a normal static method(this answer) or you use it as extension method(Ahmed's answer).
6

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"}

2 Comments

string[] a = new string[] {"1","2","2"}; string[] b = new string[] {"1","2"}; string[] DifferArray = a.Except(b).ToArray(); DifferArray.Length; // 0 it's bad case
Longer list needs to be in front or it won't work, eg LongerList.Except(shorterList).ToArray();
3

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)

1 Comment

Thanks, probably won't use that this time, but it is a nifty option.
-2
        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");
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.