0

How to check whether array2 is subset of array1 or not? In other words I want to check whether all elements of array2 are present in array1 or not? I want solution in Lambda or Linq.

int[] array1 = {6, 3, 1, 4, 5, 2};
int[] array2 = {1, 2, 3};
1
  • thank you for the modification and correction for my boring sentence and grammatical mistakes :D Commented Sep 12, 2012 at 14:04

3 Answers 3

5

If I understood your question:

using System.Linq;

if (!array2.Except(array1).Any())
{
    ...validated!
}
Sign up to request clarification or add additional context in comments.

8 Comments

hello @Alessandro from above array1 and array2 the result is "true" when i tested the array with elements below.. the result is "false" any idea? thank you int[] array1 = { 6, 3, 1, 4, 5, 2 }; int[] array2 = { 11, 12, 6, 4, 3}; if (!array2.Except(array1).Any()) { Console.WriteLine("true"); } else { Console.WriteLine("false"); }
It's correct because not all the elements of array2 exist inside array1.
mmhmm i already tested the code with another elements.. the result is false
yes.. from the first example of mine the result is true.. but i want to check the array2 if exist in array1 elements in any order of elements
To check for one match try this: if (arrayElement2.Intersect(arrayElement1).Any())
|
1

Another simple LINQ, you can use All to check whether all items of array2 in array1:

if (array2.All(array1.Contains))
{
    // array2 is subset of array1
}

2 Comments

if you use your given function and the elements is like from my first example the result is true, but if you try to change the elements in any order the result is false. try this int[] array1 = { 6, 3, 1, 4, 5, 2 }; int[] array2 = { 11, 1, 2, 3}; var s = array2.All(array1.Contains); the correct answer is from @Alessandro if (array2.Intersect(array1 ).Any())
@spajce: int[] array1 = { 6, 3, 1, 4, 5, 2 }; int[] array2 = { 11, 1, 2, 3}; it is false of course because 11 does not belong to array1
1

Try with,

 int[] array1 = { 6, 3, 1, 4, 5, 2 };
 int[] array2 = { 1, 2, 3 };

 bool isSubset = array2.Count(o => array1.Contains(o)).Equals(array2.Count()) ? true : false;

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.