Mr. 笑哥
Mr. 笑哥

Reputation: 283

Dynamic Linq Group By

I am currently building reports and have a need to Group columns dynamically, depending on user's choice. Now, assuming that the situation is fixed on all columns, the query would be as follows:

var groupedInvoiceItems = invoiceItems.GroupBy(x => new { x.SalesInvoice.name, x.SalesInvoice.currencyISO, x.CatalogProduct });

Doing so would return results as desired, IGrouping. I would then run a loop to process the necessary data as below:

foreach (var groupedInvoiceItem in groupedInvoiceItems)
{
    // Perform work here
}

Now, the headache comes in when I try to make the Grouping dynamic by using Dynamic Linq. The query is as follows:

var groupedInvoiceItems = invoiceItems.GroupBy("new (SalesInvoice.name, SalesInvoice.currencyISO, CatalogProduct)", "it");

The problem with this is that it does not return IGrouping anymore. Hence, my foreach loop no longer works. Is there any solution to the matter? I tried casting IGrouping to the Dynamic query but to no avail. Help is needed urgently.

Upvotes: 1

Views: 3106

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109261

The result of the GroupBy is an IEnumerable<IGrouping<DynamicClass,InvoiceItem>>, so you can proceed by something like:

foreach (IGrouping<DynamicClass,InvoiceItem> invoiceItemGroup in groupedInvoiceItems)
{

}

Upvotes: 4

HMB
HMB

Reputation: 21

You should do the grouping then select the specified attributes to iterate throw them in the foreach loop. Try this out:

var groupedInvoiceItems = invoiceItems.GroupBy("SalesInvoice.name","it").GroupBy("SalesInvoice.currencyISO","it").GroupBy("CatalogProduct","it").Select("new (it.SalesInvoice.name,it.SalesInvoice.currencyISO,it.CatalogProduct)");

Hope this works.

Upvotes: -1

Related Questions