2016-06-22 19 views
2

我有一個關於LINQ和foreach的問題。可以說我有一個簡單的DB有三個表格(ingredient,recipe和多對多關係ingredientinrecipe)。他們都有簡單的id和名字結構。LINQ語句獲取每個配方的ingridients列表

我正在運行控制檯應用程序,其中用戶可以輸入兩個ingredients例如

egg, flour 

我怎麼會結構中的LINQ條款要經過所有的食譜,這些地方都將是內部的。

我使用UOW一起構建的一切,所以我可以做uow.Ingridients.All ...等等等等

我想我需要從ingridientinrecipe表接近它。

這將是以下的東西:

var recipes = uow.ingridientinrecipe.All.Where(a => a.Ingridient.IngridientName.Contains(... 

但是,當且僅當用戶進入一個ingridient這個工程。我將如何擴展它以使用兩個無限輸入。

我添加了我迄今爲止所做的。

var line = Console.ReadLine(); 
while (line.ToLower().Trim() != "exit") 
{ 
    var ingridients= line.Split(','); 
    Console.WriteLine("\nAre you looking for following receipes:"); 
    foreach (var ingridient in ingridients) 
    { 
     var recipes= _uow.IngridientInRecipe.All.Where(a => a.Ingridient.IngridientName.Contains(ingridient)).ToList(); 
     foreach (var recipe in recipes) 
     { 
      Console.WriteLine(recipe.Recipes.RecipeName); 
     } 
     Console.WriteLine(); 
     line = Console.ReadLine(); 
} 

表結構,是ASKED

public class Recipe 
{ 
    public int RecipeId{ get; set; } 

    public string RecipeName{ get; set; } 

    public virtual List<IngridientInRecipe> IngridientInRecipe{ get; set; } 
} 


public class Symptom 
{ 
    public int IngridientId{ get; set; } 
    public string IngridientName{ get; set; } 

    public virtual List<IngridientInRecipe> IngridientInRecipe{ get; set; } 

} 

public class IngridientInRecipe 
{ 

    public int IngridientInRecipeId{ get; set; } 

    public int RecipeId{ get; set; } 
    public virtual Recipe Recipe{ get; set; } 

    public int IngridientId{ get; set; } 
    public virtual Ingridient Ingridient{ get; set; } 
} 
+0

我t的拼寫「成分」 –

+0

我一直在試圖寫解決方案,但我需要你分享表結構,請。 – Veverke

+0

@Veverke已添加! –

回答

3

您可以使用Intersect

var line = Console.ReadLine(); 
while (line.ToLower().Trim() != "exit") 
{ 
    var ingridients = line.Split(','); 
    Console.WriteLine("\nAre you looking for following receipes:"); 
    var recipes = _uow.IngridientInRecipe.All; 
    foreach (var ingridient in ingridients) 
    { 
     recipes = recipes.Intersect(_uow.IngridientInRecipe.All.Where(a => a.Ingridient.IngridientName.Contains(ingridient))); 
    } 
    foreach (var recipe in recipes.ToList()) 
    { 
     Console.WriteLine(recipe.Recipes.RecipeName); 
    } 
    Console.WriteLine(); 
    line = Console.ReadLine(); 
} 
+0

你好!謝謝您的回答。它經歷了第一次,但它第二次通過ingridients foreach它沒有找到任何東西。 即使配方明確有ingridient! –

+0

問題似乎是第二次通過該列表,配方成分只有第一次進入列表的ingridients。我假設不知何故,我需要在每個特定配方中加入每種成分。 有什麼想法? –

0

你可以使用一個PredicateBuilderLinqKit(我有這個沒有隸屬關係):

var ingredients = ingredientList.ToLower().Split(new [] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries); 
var predicate = PredicateBuilder.False<Recipe>(); 

foreach (var ingredient in ingredients) 
{ 
    string temp = ingredient; // To avoid passing the loop variable into a closure 
    predicate = predicate.Or(r => r.Ingredients.Contains(temp); 
} 

reportQuery = reportQuery.Where(predicate);