'LINQ - How to get recipes with all ingredients match

I'm having trouble finding recipes that contain all of selected ingredients.

Models:

Recipe

public int Id { get; set; }
[StringLength(64)]
public string Name { get; set; }
public string Description { get; set; }
[StringLength(256)]
public string CoverURL { get; set; }
public int PreparationTime { get; set; }
public DateTime AddedDate { get; set; }
public RecipeCategory Category { get; set; }
public List<RecipeImage> Images { get; set; }
public List<RecipeIngredient> Ingredients { get; set; }
public List<RecipeSpice> Spices { get; set; }

Ingredient

public int Id { get; set; }
[StringLength(64)]
public string Name { get; set; }
public List<RecipeIngredient> Recipes { get; set; }

[NotMapped]
public bool IsSelected { get; set; }

RecipeIngredient

public int Id { get; set; }
public double Quantity { get; set; }
public  Unit Unit { get; set; }
public Recipe Recipe { get; set; }
public Ingredient Ingredient { get; set; }

And I tried

List<Ingredient> selectedIngredients = new List<Ingredient>();
selectedIngredients = _vm.Ingredients.Select(x => x).Where(x => x.IsSelected).ToList();

List<Recipe> recipes = new List<Recipe>();
recipes = _vm.Recipes.Where(x => selectedIngredients.Contains(x.Ingredients));

But it return a error:

cannot convert from 'System.Collections.Generic.List<RecipeApp.Model.RecipeIngredient>' to 'RecipeApp.Model.Ingredient'

I know it's a problem becouse "selectedIngredients" is a List of Ingredients, and a "x.Ingredients" is a list of RecipeIngredients. But I can't do it properly.

I did it, but maybe someone will do it better?

        List<Recipe> recipes = new List<Recipe>();
        List<Ingredient> selectedIngredients = new List<Ingredient>();
        
        selectedIngredients = _vm.Ingredients.Select(x => x).Where(x => x.IsSelected).ToList();
        var recipeIngredients = _vm.Recipes.Select(r => r.Ingredients).ToList();
        
        foreach(var ingredientsList in recipeIngredients)
        {
            var recipe = ingredientsList.Select(x => x.Recipe)
                                        .Where(u => ingredientsList
                                            .Select(l => l.Ingredient.Id)
                                            .Intersect(selectedIngredients
                                                .Select(l2 => l2.Id))
                                            .Contains(u.Id))
                                        .FirstOrDefault();

            if (recipe != null)
                recipes.Add(recipe);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source