简单的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.Ingredient.name。希望有一些直接的方法来引用这些项目没有循环。 Linq表达式很好。 (当我尝试使用Linq时,我最终更改了值的副本,而不是值本身.LOL)。
答案 0 :(得分:2)
你正在寻找selectmany,它可以采用多个深度的可数,并将它们变成一个联合的结果集,在一个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";
答案 1 :(得分:1)
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 :(得分:0)
Linq查询:
Ingredient ing = theRecipe.RecipeSteps.Ingredients
.FirstOrDefault(i =>
i.RecipeId == 2 &&
i.RecipeStepId == 14 &&
i.IngredientId == 5);
if (ing != null) ing.name = "New Name";