2013-04-17 17 views
0

我需要返回具有部分(X)的所有記錄(項目),所以我可以用一組或.GroupBy之後如何查找使用LINQ有共同部分的項目的所有行?

在使用該彙總數據:

ItemName PartName 
1  A 
1  B 
2  A 
3  C 

所以項目1有兩個部分(A,B),等等

我需要一個LINQ查詢,將 - 發現,有部分A的所有項目(即項目1和2) - 返回所有行對所有這些項目

1  A 
1  B 
2  A 

請注意,最終結果返回行(1B),因爲Item1具有PartA,因此我需要返回Item1的所有行。

我一直在尋找這樣的:

let items = from data in summary where data.PartName == A select new { data.ItemName } // to get all the items I need 

不過,現在我有一個名單,我需要用它來獲取所有的所有項目行上市了,我似乎無法圖出來...

實際的源代碼(僅供參考): 注: 配方=項目 成分= PART (我只是想更簡單)

  ViewFullRecipeGrouping = (
       from data in ViewRecipeSummary 
       group data by data.RecipeName into recipeGroup 
       let fullIngredientGroups = recipeGroup.GroupBy(x => x.IngredientName) 
       select new ViewFullRecipe() 
       { 
        RecipeName = recipeGroup.Key, 
        RecipeIngredients = (
         from ingredientGroup in fullIngredientGroups 
         select new GroupIngredient() 
         { 
          IngredientName = ingredientGroup.Key 
         } 
        ).ToList(), 
        ViewGroupRecipes = (
         from data in ViewRecipeSummary 

         // this is where I am looking to add the new logic to define something I can then use within the next select statement that has the right data based on the information I got earlier in this query. 
         let a = ViewRecipeSummary.GroupBy(x => x.RecipeName) 
          .Where(g => g.Any(x => x.IngredientName == recipeGroup.Key)) 
          .Select(g => new ViewRecipe() 
           { 
            RecipeName = g.Key, 
            IngredientName = g.Select(x => x.IngredientName) 
           })                 

         select new GroupRecipe() 
         { 
      // use the new stuff here 

         }).ToList(), 
       }).ToList(); 

任何幫助將不勝感激。 謝謝,

回答

1

我相信這你想要做什麼:

var data = /* enumerable containing rows in your table */; 
var part = "X"; 
var items = new HashSet<int>(data 
    .Where(x => x.PartName == part) 
    .Select(x => x.ItemName)); 
var query = data.Where(x => items.Contains(x.ItemName)); 

如果我理解在最後的評論,我相信這也是你想要做什麼:

var query = data 
    .GroupBy(x => x.ItemName) 
    .Where(g => g.Any(x => x.PartName == part)) 
    .Select(g => new 
    { 
     ItemName = g.Key, 
     PartNames = g.Select(x => x.PartName) 
    }); 
+0

你可以做第二個使用LET或INTO語句?我的想法是我需要將其嵌入到現有的LINQ語句中,因此我無法創建一個新的var分隔符。 – JSchwartz

+0

@JSchwartz我不明白評論。你可以用更多的細節來增加你的問題,也可以通過「嵌入到現有的LINQ語句中」來表達你的意思嗎? –

+0

在你的例子中,PartNames是什麼? – JSchwartz

相關問題