2

I want to compare 2 string arrays, to check if elements are the same (order is not necessarily the same).

string[] original = { "I", "IV", "VI", "VIII" };
string[] forComparisson = { "I", "IV", "VIII", "VII" };

//works, but isn't reasonable for long array:
if (
                original.Contains(forComparisson [0]) &&
                original.Contains(forComparisson [1]) &&
                original.Contains(forComparisson [2]) &&
                original.Contains(forComparisson [3])
){...}
//could us a loop...

Is there a built-in method to do such comparissons? Thanks.

pxs
  • 77
  • 6
  • 1
    Does this answer your question? [Easiest way to compare arrays in C#](https://stackoverflow.com/questions/3232744/easiest-way-to-compare-arrays-in-c-sharp) (also: have you _heard_ of search engines?) – Franz Gleichmann Oct 23 '20 at 12:11
  • 3
    `if(original.Length == forComparison.Length && original.Intersect(forComparison).Count() == original.Length)` – Gusman Oct 23 '20 at 12:12
  • Dupe of [Comparing two collections for equality irrespective of the order of items in them](https://stackoverflow.com/questions/50098/comparing-two-collections-for-equality-irrespective-of-the-order-of-items-in-the)? – stuartd Oct 23 '20 at 12:43

2 Answers2

2

Well you could first check whether they are of same length and utilize a HashSet<T> collection that has fast O(1) lookups:

string[] original = { "I", "IV", "VI", "VIII" };
string[] forComparisson = { "I", "IV", "VIII", "VII" };
var hashset = new HashSet<string>(original);

var areTheSame = original.Length == forComparisson.Length && forComparisson.All(hashset.Contains);
Fabjan
  • 13,506
  • 4
  • 25
  • 52
2

At the bottom of your code, you have a comment:

//could us a loop...

Why not do that?

static bool ArraysEquals(String[] A, String[] B)
{
    bool result = (A.Length == B.Length);
    if (result)
    {
        foreach(String X in A)
        {
            if (!B.Contains(X))
            {
                return false;
            }
        }
    }
    return result;
}

Fancier LINQ constructs like Intersect are going to have to enumerate all the items, ~somehow~, as well...

*Note: These types of problems bring up the classic memory vs. speed debate. For very large arrays, my approach will be SLOW using Contains(), but will not incur any significant memory usage increases. Fabjans solution using HashSet will be FAST (after a possible slow initial population of the Hashset), but will use a ton more memory.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Thanks. I asked because I wanted to know if there was a method already available. Will mark your answer as correct for hellping me out to clarify speed vs memory too. Regards. – pxs Oct 23 '20 at 12:55