Search code examples
c#linqdynamiclinq-group

Dynamic Grouping Using LINQ


Please have a look at below example. The Group Clause has to be dynamic. Can you please guide me how this can be achieved. i.e. the row

{ r.Portfolio, r.DataType }  

has to be constructed dynamically.

Not sure how I can tweak the solution as given at blog 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();
}

Solution

  • 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.