1

I have 2 int arrays, arr1, and arr2 eg, what is the most efficient way to verify that the arr1 contains All items that arr2 contains. Preferentially returning bool.

eg.

arr1 = [1,2,3,4]
arr2 = [1,2,3,4,5,6,9]
 //return true;

arr1 = [1,2,3,4,10]
arr2 = [1,2,3,4,5,6,9]
 //return false;

I did It with foreach but I want anything besides brute-force foreach, if is possible.

우두머리
  • 545
  • 2
  • 18

1 Answers1

9

What about something like:

bool subset = !arr1.Except(arr2).Any();

Would probably be smoothly implemented as an extension method like this:

public static bool ContainsAll<T>(this List<T> list, List<T> other)
{
    return !other.Except(list).Any();
}

Usage would then be:

bool subset = arr2.ContainsAll(arr1);
Simon Karlsson
  • 4,090
  • 22
  • 39