对象之间的嵌套查询

时间:2018-01-27 02:43:34

标签: c# linq nested

我有一个特定的问题,在普通列表上使用嵌套查询。

我有2个模型类:

public class IngridientModel
{
    public long Id { get; set; }
    public string Ingredient { get; set; }
}

public class RecipesModel
{
    [Key]
    public long Id { get; set; }
    public string RecipyName { get; set; }
    public string Description { get; set; }
    public List<OwnedIngredientsModel> Ingredients { get; set; }
}

每个类别的对象都可以包含多种成分。

现在我创建了2个列表:

清单1:我拥有的成分和可用的hava

  1. 香蕉
  2. 苹果
  3. 马铃薯
  4. 培根
  5. 水稻
  6. 清单2:食谱清单

    1. 水果派(需要苹果和香蕉)
    2. 快餐(需要米饭和培根)
    3. Spaghetti bolonese(需要培根和我没有的东西)
    4. 现在我想创建第3个列表。 该列表只能包含我目前拥有的配料(列表1)的配方,并且不应包含我目前没有的配方食谱。所以在上面的例子中,我的查询应该只产生Fruit pie和Fast dinner的食谱。

      这是我尝试做嵌套查询的方法

          public void WhatCanICook()
          {
              // List of recipes i can make
              List<RecipesModel> myRecipes = new List<RecipesModel>();
      
              // list of ingredients
              var myIngredients = ListViewIngredients.ToList();
      
              // list of all recipies, each recipy contains many ingredients
              var allRecipies = ListViewAllRecipies.ToList();
      
              // query, i would like to only list recipies with ingredients i own
              foreach (var item in myIngredients)
              {
                  var result = allRecipies.Where(p =>
                      JsonConvert.SerializeObject(p.Ingredients) == JsonConvert.SerializeObject(item));
              }
          }
      

      但是这个查询没有做我想要它做的事情:(

1 个答案:

答案 0 :(得分:0)

您可以使用类似......

之类的内容进行查询
allRecipes.Where(r => r.Ingredients.All(i => myIngredients.Any(m => m.Id == i.Id)));

如果具有相同Id的Ingredient对象保证引用同一个对象,您可以将其略微缩短为...

allRecipes.Where(r => r.Ingredients.All(i => myIngredients.Contains(i)));

如果由于存储在列表中并且涉及嵌套循环而存在大量成分,则两个查询都会出现严重的性能问题。这可以通过使用集合来改进。

相关问题