5

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.

1 Answer 1

16

Use Enumerable.Except

bool allInEntered = !enteredItems.Except(allPossible).Any();
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's a sweet one liner.

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.