以下是我的linq表达式:
return from c in db.RecipeIngredients
join d in db.Ingredients on c.IngredientID equals d.IngredientsID
where c.RecipeID.Equals(recipeID)
select (d.IngredientsID,c.Unit,c.IngredientID,c.Amount).ToList();
这应该返回成分信息行的列表。这会返回什么类型?我现在如何继续使用firstRow.ingredientName等?
答案 0 :(得分:5)
首先,我认为您的代码无法编译,您缺少两个括号:
return (from c in db.RecipeIngredients
join d in db.Ingredients on c.IngredientID equals d.IngredientsID
where c.RecipeID.Equals(recipeID)
select (d.IngredientsID,c.Unit,c.IngredientID,c.Amount)).ToList();
好的,接下来,(d.IngredientsID,c.Unit,c.IngredientID,c.Amount)
如果你在C#7.0上这是一个包含所有变量的声明元组,那么你需要在括号之间返回那些类型,就像这里一样(我将假设你的变量类型,根据需要纠正它:
public List<(int, UnitNames, int, double)> GetRecipe(int recipeId)
{
return (from c in db.RecipeIngredients
join d in db.Ingredients on c.IngredientID equals d.IngredientsID
where c.RecipeID.Equals(recipeID)
select (d.IngredientsID,c.Unit,c.IngredientID,c.Amount)).ToList();
}
要访问您访问的变量,请执行以下操作:
var recipe = GetRecipe(recipeId);
foreach(var ingredient in recipe)
{
var ingredientsId = ingredient.Item1;
var unit = ingredient.Item2;
var ingredientId = ingredient.Item3;
var amount = ingredient.Item4;
}
无论如何,我建议创建一个传递数据的类,它会产生一个非常清晰的代码:
public class Ingredient
{
public int IngredientsId { get; set; }
public UnitNames Unit { get; set; }
public int IngredientId { get; set; }
public double Amount { get; set; }
}
public List<Ingredient> GetRecipe(int recipeId)
{
return (from c in db.RecipeIngredients
join d in db.Ingredients on c.IngredientID equals d.IngredientsID
where c.RecipeID.Equals(recipeID)
select new Ingredient {
IngredientsId = d.IngredientsID,
Unit = c.Unit,
IngredientId = c.IngredientID,
Amount = c.Amount
}).ToList();
}