I am new to LINQ, but I am wondering if it is possible to use LINQ to pivot data from the following layout:
CustID | OrderDate | Qty
1 | 1/1/2008 | 100
2 | 1/2/2008 | 200
1 | 2/2/2008 | 350
2 | 2/28/2008 | 221
1 | 3/12/2008 | 250
2 | 3/15/2008 | 2150
into something like this:
CustID | Jan- 2008 | Feb- 2008 | Mar - 2008 |
1 | 100 | 350 | 250
2 | 200 | 221 | 2150
I answered similar question using linq extension method:
(+) generic implementation
(-) definitely slower than David B's
Can anyone improve my implementation (i.e. the method does the ordering of columns & rows)?
The neatest approach for this, I think, is to use a lookup:
This is most efficient way:
Check the following approach. Instead of iterating through the customers group each time for each month.
Or this one :
Complete solution:
Here is a bit more generic way how to pivot data using LINQ:
where ValueKey is a special class that represents multidimensional key:
This approach can be used for grouping by N-dimensions (n>2) and will work fine for rather small datasets. For large datasets (up to 1 mln of records and more) or for cases when pivot configuration cannot be hardcoded I've written special PivotData library (it is free):
Something like this?
GroupBy
in Linq does not work the same as SQL. In SQL, you get the key and aggregates (row/column shape). In Linq, you get the key and any elements as children of the key (hierarchical shape). To pivot, you must project the hierarchy back into a row/column form of your choosing.Group your data on month, and then project it into a new datatable with columns for each month. The new table would be your pivot table.