2016-03-26 66 views
0

如何在recipe=中寫DescriptionRecipe。 我試圖使用join r in Recipe on d.DishID equals r.DishID,但它給出了錯誤的結果。它擦除result1中的一個項目。Linq羣體加入

Exptected輸出:

enter image description here

namespace ConsoleApplication3 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      List<Component> Component = new List<Component>(); 
      List<Dish> Dish = new List<Dish>(); 
      List<Recipe> Recipe = new List<Recipe>(); 
      Dish.Add(new Dish { DishID = 9, CategoryID = 6, DishName = "Pork" }); 
      Dish.Add(new Dish { DishID = 10, CategoryID = 6, DishName = "Beef" }); 
      Component.Add(new Component { ComponentID = 1, DishID = 9, AmountID = "1", NameID = "1" }); 
      Recipe.Add(new Recipe { DishID = 9, RecipeID = 0, Description = "Test" }); 

      var result1 = (
      from d in Dish 
      //join r in Recipe on d.DishID equals r.DishID 
      join c in Component on d.DishID equals c.DishID into items 
      select new Item { DishID = d.DishID, components = items.ToList() recipe=} 
      ).ToList(); 
     } 
    } 
    public class Item 
    { 
     public int DishID { get; set; } 

     public string DishName { get; set; } 

     public string recipe { get; set; } 

     public List<Component> components { get; set; } 
    } 

    public partial class Component 
    { 
     public int ComponentID { get; set; } 
     public int DishID { get; set; } 
     public string AmountID { get; set; } 
     public string NameID { get; set; } 
    } 

    public partial class Dish 
    { 
     public int DishID { get; set; } 
     public int CategoryID { get; set; } 
     public string DishName { get; set; } 
    } 
    public partial class Recipe 
    { 
     public int RecipeID { get; set; } 
     public int DishID { get; set; } 
     public string Description { get; set; } 
    } 
} 
+0

'但它給錯誤的結果。「它是什麼?示例輸入?預期產出? – Eser

+0

更正你的代碼,讓它運行,現在它不會從你所說的給出一個關於如何在linq中進行左連接的答案,但是你的代碼不能編譯,顯示當前正在工作的代碼 – konkked

+0

是從Dish的關係=> 1到1配方?你的編輯讓我感到困惑 – konkked

回答

2

你想要做一個左連接

要做到這一點,你需要做一些額外的東西在LINQ,不知道爲什麼它不是本地支持,但它不是。

 var result1 = (
     from d in Dish 
     join c in Component on d.DishID equals c.DishID into items 
     join r in Recipe on d.DishID equals r.DishID into recipes 
     select new Item { 

        DishID = d.DishID, 

        components = items.DefaultIfEmpty() 
             .Where(a=>a!=null) 
             .ToArray(), 

        recipe = recipes.DefaultIfEmpty() 
            .Where(a=>a!=null) 
            .Select(a=>a.Description) 
            .FirstOrDefault() 
     }).ToList(); 
+1

您應該在recipes.DefaultIfEmpty( )'再次將食譜弄平。然後'recipe = r?.Description'。 –

+0

@GertArnold通常在C#5中回答,除非我確定該人可以使用C#6 – konkked

+1

當然,繼續,只是指出正確的(imo)方向。 –