Dreik
Dreik

Reputation: 140

How to compare 2 Lists in Linq Query?

I have Database model

public class Dish
    {
        public int Id { get; set; }
        public String Name { get; set; }
        public Dictionary<Ingridient, int> Ingridients { get; set; }
        public List<String> Images { get; set; }
        public String  Guide { get; set; }
        public Guid User { get; set; }
        public DishType dishType { get; set; }
        public int Rate { get; set; }

        public enum DishType
        {
            Polish,
            Asian,
            Indian,
            Other
        };
    }

I'd like to get all dishes that have ingridients that are asked of from List<Ingridient>. Something like

Input List<Ingridient>

Get all Dishes where Dictionary containts all these ingridients. While Ingridient is Key.

I tried some slow solution that worked on all dishes from database but I'd like to move to query Database to make it faster.

My Solution - very slow and takes a lot of memory:

List<Dish> allDishes = Dishes.Select(n => n).ToList();
            List<Dish> Found = new List<Dish>();
            foreach(var d in allDishes)
            {
                List<Ingridient> fromDish = d.Ingridients.Keys.ToList();

                foreach(var ing in ingridients)
                {
                    if (!fromDish.Contains(ing))
                        break;
                }

                Found.Add(d);
            }

I'd like to recreate this behaviour as Linq query.

Upvotes: 0

Views: 923

Answers (1)

Sergei G
Sergei G

Reputation: 1570

Try

dishes.Where(dish => !ingredients.Except(dish.Ingredients).Any()).ToList();

Where !ingredients.Except(dish.Ingredients).Any() checks that all ingredients in the request list are contained in the ingredients of the dish.

You can fiddle with fiddle with a test here.

Upvotes: 1

Related Questions