LINQ按多个可选列分组

时间:2018-11-15 13:45:36

标签: c# .net linq

我正在努力让LINQ Group By成为我的大脑,并且我取得了进展,但我的知识有一个小缺陷。 我想按多个列进行分组,这些列我知道可以对new {}和某些字段进行处理。唯一的问题是,基于某些查询字符串值,我可能会或可能不想将它们包括在内。

我有这个:

            var groupByResults = items.GroupBy(i => new 
            { 
                i.Product.Season.SeasonID,
                i.SourceLocation.LocationID, 
                i.Product.Brand.BrandID, 
                i.Product.Category.CategoryID, 
                i.Size.SizeID 
            });

我可能希望我的匿名对象仅具有第一个字段,或最后两个字段,或其他内容-取决于浏览器中已勾选的复选框。我在考虑ExpandoObject,但是我在努力如何从i => .....

中获取有关“ i”的关系。

与我要询问的所有内容一样,只是我没有为Google找到正确的用语。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以首先包括所有可能的group by条目,然后根据您的UI选择对其中一些进行“存根”(: true):

var groupByResults = items.GroupBy(i => new 
{ 
    SeasonID = UISeasonID != null ? i.Product.Season.SeasonID : true,
    LocationID = UILocationID != null ? i.SourceLocation.LocationID : true, 
    BrandID = UIBrandID != null ? i.Product.Brand.BrandID : true, 
    CategoryID = UICategoryID != null ? i.Product.Category.CategoryID : true, 
    SizeID = UISizeID != null ? i.Size.SizeID : true 
});
相关问题