代码之家  ›  专栏  ›  技术社区  ›  Zachary Scott

简单C#List<>:给定主键,如何在List<>中查找和更新嵌套对象属性?

  •  2
  • Zachary Scott  · 技术社区  · 14 年前

    简单的IList更新问题:给定以下嵌套对象,如何更新给定主键的最深嵌套属性?

    public class Recipe {
        public int RecipeID {get;set;}     // PK
    
        public string name {get;set;}
        public IList<RecipeStep> RecipeSteps {get;set;}
    }
    
    public class RecipeStep {
        public int RecipeID {get;set;}     // PK
        public int RecipeStepID {get;set;} // PK
    
        public string name {get;set;}
        public IList<Ingredient> {get;set;}
    }
    
    public class Ingredient {
        public int RecipeID {get;set;}     // PK
        public int RecipeStepID {get;set;} // PK
        public int IngredientID {get;set;} // PK
    
        public string name {get;set;}
    }
    

    那么,如果RecipeID=2、RecipeStepID=14和IngredientID=5(这是int的值,而不是索引),我如何设置Recipe.RecipeStep.component.name呢。希望有一些直接的方法来引用这些项而不需要循环。Linq表达式很好(当我尝试Linq时,我最终更改了值的一个副本,而不是值本身。哈哈)。

    3 回复  |  直到 14 年前
        1
  •  2
  •   Amy B    14 年前
    Ingredient theIngredient =
    (
      from r in Recipes
      where r.RecipeId == 2
      from rs in r.RecipeSteps
      where rs.RecipeStepID == 14
      from ing in rs.Ingredients
      where ing.IngredientId == 5
      select ing
    ).Single()
    
    theIngredient.name = theName;
    
        2
  •  2
  •   Jimmy Hoffa    14 年前

    你要找的是selectmany,它可以对ienumerable进行多个深度的处理,并将它们展平到一个ienumerable中的联合结果集,一个selectmany()获取所有成分,然后根据你的条件执行where()

    Ingredient ing = theRecipe.RecipeSteps.SelectMany((recipeStep) => recipeStep.Ingredient)
        .FirstOrDefault((ingredient) =>
            ingredient.RecipeId == 2 &&
            ingredient.RecipeStepId == 14 &&
            ingredient.IngredientId == 5);
    
    ing.name = "pretty flowers";
    
        3
  •  0
  •   Andreas Rehm    14 年前

    Linq查询:

    Ingredient ing = theRecipe.RecipeSteps.Ingredients
        .FirstOrDefault(i =>
            i.RecipeId == 2 &&
            i.RecipeStepId == 14 &&
            i.IngredientId == 5);
    
    if (ing != null) ing.name = "New Name";