3

If the ingredients of a pizza exist among allIngred, the result would give true by using LINQ. How would I go about doing this?

string[] allIngred = {
    "oil", "yeast", "wheat-flour", "salt", "oil", "baking-powder",
    "wheat-flour", "salt", "sugar", "milk"
};
string[] pizza = { "oil", "yeast", "wheat-flour", "salt" };

6 Answers 6

3

You can use a combination of the All and Contains methods to check that all items in pizza exist in allIngred:

bool result = pizza.All(i => allIngred.Contains(i));
Sign up to request clarification or add additional context in comments.

Comments

2

I'm not a 100% sure what you mean, but I hope this helps:

if (pizza.Intersect(allIngred).Count() == pizza.Count()){
     Console.WriteLine("All pizza ingredients exist");
}

Comments

1

It sounds like you want to use some of Linq's set operators. These will get you started in the right direction.

In particular, check out Linq's Intersect operator. If the result of the intersect is equal to the ingredients for the pizza you care about, then you know that you have all of the ingredients you need.

Comments

1
bool result = pizza.Intersect(allIngred).SequenceEqual(pizza);

Intersect() gives you all of the members that are shared between the two arrays, and SequenceEqual() identifies whether the result set is the same as the provided argument (in this case you want to see if all pizza ingredients are in allIngred).

Note that this will not necessarily work if you reverse the arrays:

bool result = allIngred.Intersect(pizza)…

because the result set of Intersect will be ordered according to the first argument, and you need the results to match pizza.

Adding ordering explicitly would be safer for dealing with IEnumerable<T>, where ordering is not guaranteed:

bool result = pizza.Intersect(allIngred).OrderBy(x => x).SequenceEqual(pizza.OrderBy(x => x));

For this particular requirement, you can optimize by just checking the Count() of items after the call to Intersect() against the length of the pizza array.

Comments

1

While there are several possible approaches using LINQ, some of them are more expensive than others. For something that will usually run faster than intersection and "all" approaches, try the following:

bool result = !pizza.Except(allIngred).Any();

Comments

0

Converting these two arrays into HashSet<string> would be a better way when you want to do more of these types of operations.

ISet<string> allIngred = new HashSet<string>() { ... items ...};
ISet<string> pizza = new HashSet<string>() { ... items ... };

bool haveIngredients = pizza.IsSubset(allIngred);

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.