2017-12-24 6 views
-6

次は私の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(); 

これは成分情報の列のリストを返すべきです。これが返すタイプは何ですか?今、firstRow.ingredientNameなどを使用するにはどうしたらいいですか?あなたはそのすべての変数と宣言型のタプルですC#7.0、にしている場合(d.IngredientsID,c.Unit,c.IngredientID,c.Amount)、次、

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

OK:

+2

をコンパイルしていますか?いくつかのアイデアについては、次の記事を見てください:https://stackoverflow.com/questions/534690/return-anonymous-type-results –

+0

あなたは[ask]を読んで[tour]を取るべきです。スコアが0以下のものすべてを含む6つの投稿は、すぐに参加を制限します。 – Plutonix

答えて

4

まず、私はあなたが2つの括弧が欠落している、あなたのコードがコンパイルされませんと思います

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

} 

あなたは、このようにアクセスも変数にアクセスするには:あなたはここのような括弧の間のタイプは、(必要に応じて、私はそれは、あなたのVARSの種類を想定し、正しいだろう)ことを返す必要がありますいずれの場合においても

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

} 
関連する問題