[英]Dynamic Grouping Using 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<DecisionSupportData> lstAllDecSupp = decisionSupportDataBindingSource.DataSource as List<DecisionSupportData>;
List<DecisionSupportData> 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<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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.