I’m trying to rewrite some old SQL into LINQ to SQL. I have a sproc with a GROUP BY WITH ROLLUP but I’m not sure what the LINQ equivalent would be. LINQ has a GroupBy but it doesn’t look like it supports ROLLUP.
A simplified example of the results I’m trying to get would be something like this:
+-----------+---------------+--------------------+ | City | ServicePlan | NumberOfCustomers | +-----------+---------------+--------------------+ | Seattle | Plan A | 10 | | Seattle | Plan B | 5 | | Seattle | All | 15 | | Portland | Plan A | 20 | | Portland | Plan C | 10 | | Portland | All | 30 | | All | All | 45 | +-----------+---------------+--------------------+
Any ideas on how I could get these results using LINQ to SQL?
I figured out a much simpler solution. I was trying to make it way more complicated than it needed to be. Rather than needing 3-5 classes/methods I only need one method.
Basically, you do your sorting and grouping yourself and then call
WithRollup()to get aList<>of the items with sub-totals and a grand total. I couldn’t figure out how to generate the sub-totals and grand total on the SQL side so those are done with LINQ to Objects. Here’s the code:And an example of how to use it: