使用LINQ进行动态分组

请看下面的例子。 集团条款必须是动态的。 能否指导我如何实现这一目标。 即行

{ r.Portfolio, r.DataType } 

必须动态构建。

不知道如何调整解决方案,如博客http://jonahacquah.blogspot.com/2012/02/groupby-multiple-columns-using-dynamic.html所示。

 public class DecisionSupportData { public string Portfolio { get; set; } public string BucketName { get; set; } public string DataType { get; set; } public string ChildPortfolio { get; set; } } public void PopulateData() { List lstAllDecSupp = decisionSupportDataBindingSource.DataSource as List; List lstRmgAmt = (from r in lstAllDecSupp.AsEnumerable() where r.DataType == "P" group r by new { r.Portfolio, r.DataType } into gg select new DecisionSupportData { DataType = gg.Key.DataType, Portfolio = gg.Key.Portfolio, }).ToList(); } 

如Scott Gu的原始博客中所述,DynamicLinq库似乎可以解决您的问题。 只需将GroupBy扩展方法与字符串值一起使用即可。

或者你可以挖掘他们的ExpressionParser类,看看它在做什么。

以下内容适用于您的示例,但如果您的实际示例更复杂,则可能无法正常工作/扩展。

 // bools to indicate which columns you want to group by bool groupByPortfolio = true; bool groupByDataType = true; bool groupByBucketName = false; bool groupByChildPortfolio = false; List 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();