Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check string array elements only contain elements in another array

Tags:

c#

linq

I have 2 arrays

string[] allPossible = {"ID","Age","FirstName","LastName","Gender","Kudos"};
string[] enteredItems = {"Age", "LastName"};

I want to check the array enteredItems only contains elements found in the array allPossible. I want to do this with LINQ.

I have looked

allPossible.Any(el => enteredItems .Contains(el));

and

allPossible.Intersect(enteredItems).Any();

Instead I loop thru the enteredItems and use Array.IndexOf(allPossible, x) == -1 return false.

The top data sample would return would return true... however if only 1 element in the enteredItems array is not in the allPossible array then there will be a false. ie.

string[] allPossible = {"ID","Age","FirstName","LastName","Gender","Kudos"};
string[] enteredItems = {"Age", "Geeky"};

would be false because 1 element in the 'enteredItems' array does not exist in the 'allPossible' element.

There must be a LINQ query to do this.

like image 637
matthewbaskey Avatar asked Sep 10 '13 21:09

matthewbaskey


1 Answers

Use Enumerable.Except

bool allInEntered = !enteredItems.Except(allPossible).Any();
like image 182
Tim Schmelter Avatar answered Sep 22 '22 17:09

Tim Schmelter