I would like to know to to write most efficient LINQ (EDIT: to Entities) query with a list as a condition. Here is the thing.
Lets say we have the following data structure:
public class Recipe
{
public int Id;
public string Name;
public List<Ingredient> IngredientList;
}
public class Ingredient
{
public int Id;
public string Name;
}
Now, I would like to make a query which will search all the Recipes which have ALL given ingredients.
public List<Recipe> GetRecipesWhichHaveGivenIngredients(List<Ingredients> ingredients)
{
List<Recipe> recipes;
using (DataContext context = new DataContext())
{
//efficient LINQ query goes here
recipes = context.Recipes.Where(recipe => /*medaCode recipe.IngredientList.Contains(ingredients) */).ToList();
}
return recipes;
}
Basically this is the problem how to determine whether a given set is a subset of another set.
I have tried with the following query (the main idea is usage of the Intersect operation):
List<Recipe> recipes = dataContext.Recipes.Include("Ingrediens").Where(rec => rec.IngredientList.Select(ingr => ingr.Id).Intersect(ingredients.Select(sy => sy.Id)).Count() == ingredients.Count).ToList();
But I get the following error:
Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.