如何使用LINQ查找具有共同部分的所有项目行?

时间:2013-04-17 04:07:42

标签: linq

我需要返回所有包含部分(X)的记录(项目),以便我可以在组中使用它或者之后使用.GroupBy

使用此摘要数据:

ItemName PartName
1        A
1        B
2        A
3        C

所以Item1有两个部分(A,B)等......

我需要一个LINQ查询 - 找到所有具有A部分的项目(即项目1和2) - 返回所有这些项的所有行

1        A
1        B
2        A

请注意,最终结果返回了行(1 B),因为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 个答案:

答案 0 :(得分: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)
    });