2014-12-19 182 views
2

所以前提是我有一個名爲recipes的表,每個食譜都有成分。我想建立一個購物清單。嵌套連接查詢的Linq語法

目前我在做什麼是: -

List<ingredient> UsedIngredients = new List<ingredient>(); 

foreach (var item in this.Recipes) 
{ 
    foreach (var ingredient in item.ingredients) 
    { 
     if (!UsedIngredients .Contains(ingredient)) 
     { 
      UsedIngredients .Add(ingredient); 
     } 
    } 
} 

我知道我可以簡化它歸結爲

List<ingredient> UsedIngredients = new List<ingredient>(); 

foreach (var item in this.Recipes) 
{ 
    foreach (var ingredient in item.ingredients.Where(ingredient => !UsedIngredients .Contains(ingredient))) 
    { 
     UsedIngredients.Add(ingredient); 
    } 
} 

很簡單,但我想一定有短手的方法在linq中執行此操作,即獲取用於所有選定食譜的所有成分的列表。

同時請注意,

Recipes的類型爲recipe recipe類型的列表有一個屬性成分,其是使用中間許多一對多連接表(由EF來分解走了加入到成分表只是.ingedients

回答

3

所以你試圖從食譜得到一個獨特的成分集合。

var usedIngredients = 
    (from recipe in this.Recipes 
    from ingredient in recipe.ingredients 
    select ingredient).Distinct().ToList(); 
+0

謝謝!我甚至不知道你可以在一個linq查詢中使用兩個命令 - 這使得其他一些事情也變得更加容易;) – 2014-12-19 00:50:44

0
 public void Test() 
    { 
     List<Recipes> recipes = new List<Recipes>(); 
     List<Ingredient> UsedIngredients = new List<Ingredient>(); 
     UsedIngredients = (from a in recipes where UsedIngredients.Contains(a.ingredient) select a.ingredient).ToList(); 
    } 

請試試這個