Dynamic Grouping Using LINQ

牧云@^-^@ 提交于 2019-12-06 05:26:51

The DynamicLinq library would appear to solve your issue, as mentioned in Scott Gu's original blog. Just use the GroupBy extension method with a string value.

Or you could dig into their ExpressionParser class and see what it's doing.

The following should work with your example, but may not work/scale up very well if your real-life example is more complicated.

// bools to indicate which columns you want to group by 
bool groupByPortfolio      = true;
bool groupByDataType       = true;
bool groupByBucketName     = false;
bool groupByChildPortfolio = false;


List<DecisionSupportData> lstRmgAmt
    = (from r in lstAllDecSupp.AsEnumerable()
       where r.DataType == "P"
       group r by new 
       { 
            Portfolio       = groupByPortfolio      ? r.Portfolio       : null ,
            DataType        = groupByDataType       ? r.DataType        : null , 
            BucketName      = groupByBucketName     ? r.BucketName      : null ,
            ChildPortfolio  = groupByChildPortfolio ? r.ChildPortfolio  : null 
        }
       into gg 

       select new DecisionSupportData
       {
            Portfolio       = gg.Key.Portfolio,
            DataType        = gg.Key.DataType,
            BucketName      = gg.Key.BucketName,
            ChildPortfolio  = gg.Key.ChildPortfolio  

        }
 ).ToList(); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!