linq语法:返回的类型是什么?现在如何继续使用firstRow.ingredientName等?

Plo*_*oni -6 c# linq

以下是我的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();
Run Code Online (Sandbox Code Playgroud)

这应该返回成分信息行的列表。返回的类型是什么?现在如何继续使用firstRow.ingredientName等?

Gus*_*man 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();
Run Code Online (Sandbox Code Playgroud)

好的,接下来,(d.IngredientsID,c.Unit,c.IngredientID,c.Amount)如果您使用的是C#7.0,它是一个包含所有变量的声明性元组,那么您需要在括号之间返回该类型,例如此处(我将假设您的var类型,请根据需要对其进行更正):

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();

}
Run Code Online (Sandbox Code Playgroud)

要访问变量,您需要像这样:

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;
}
Run Code Online (Sandbox Code Playgroud)

无论如何,我建议创建一个类来传递数据,这将导致非常清晰的代码:

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();

}
Run Code Online (Sandbox Code Playgroud)