matthewbaskey
matthewbaskey

Reputation: 1037

Check string array elements only contain elements in another array

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.

Upvotes: 5

Views: 1454

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

Use Enumerable.Except

bool allInEntered = !enteredItems.Except(allPossible).Any();

Upvotes: 16

Related Questions