Pivot C# Array or DataTable: Convert a Column To a Row with LINQ
My previous post explains how to convert a column to row in JavaScript array. In this post, we will do the same thing but with C# Array and DataTable using the power of LINQ or Lambda expression. For simplicity, I am using the same data.

C# Array To Pivot DataTable:
Here is the C# array object:
| vardata = new[] {               new{ Product = "Product 1", Year = 2009, Sales = 1212 },              new{ Product = "Product 2", Year = 2009, Sales = 522 },              new{ Product = "Product 1", Year = 2010, Sales = 1337 },              new{ Product = "Product 2", Year = 2011, Sales = 711 },              new{ Product = "Product 2", Year = 2012, Sales = 2245 },              new{ Product = "Product 3", Year = 2012, Sales = 1000 }          }; | 
On Googling, I found the following generic method in StackOverflow thread.
| public staticDataTable ToPivotTable<T, TColumn, TRow, TData>(    thisIEnumerable<T> source,    Func<T, TColumn> columnSelector,    Expression<Func<T, TRow>> rowSelector,    Func<IEnumerable<T>, TData> dataSelector)        {            DataTable table = newDataTable();            varrowName = ((MemberExpression)rowSelector.Body).Member.Name;            table.Columns.Add(newDataColumn(rowName));            varcolumns = source.Select(columnSelector).Distinct();            foreach (varcolumn incolumns)                table.Columns.Add(newDataColumn(column.ToString()));            varrows = source.GroupBy(rowSelector.Compile())                             .Select(rowGroup => new                             {                                 Key = rowGroup.Key,                                 Values = columns.GroupJoin(                                     rowGroup,                                     c => c,                                     r => columnSelector(r),                                     (c, columnGroup) => dataSelector(columnGroup))                             });            foreach (varrow inrows)            {                vardataRow = table.NewRow();                varitems = row.Values.Cast<object>().ToList();                items.Insert(0, row.Key);                dataRow.ItemArray = items.ToArray();                table.Rows.Add(dataRow);            }            returntable;        } | 
You can create a static class for extension methods and put it there.
To convert Year values to columns and get Pivot DataTable:
To convert Year values to columns and get Pivot DataTable:
| varpivotTable = data.ToPivotTable(              item => item.Year,               item => item.Product,                items => items.Any() ? items.Sum(x=>x.Sales) : 0); | 
You will get the following output:

C# Array to Pivot Dynamic Array:
You might want to get the List<dynamic> or dynamic[] instead of getting DataTable after converting columns to rows. It is handy in ASP.NET Web API to return JSON response.
To do it, I updated the extension method to get the dynamic object. use following extension method:
|      public staticdynamic[] ToPivotArray<T, TColumn, TRow, TData>(thisIEnumerable<T> source,Func<T, TColumn> columnSelector,Expression<Func<T, TRow>> rowSelector,Func<IEnumerable<T>, TData> dataSelector)       {           vararr = newList<object>();           varcols = newList<string>();           String rowName = ((MemberExpression)rowSelector.Body).Member.Name;           varcolumns = source.Select(columnSelector).Distinct();                  cols =(new[]{ rowName}).Concat(columns.Select(x=>x.ToString())).ToList();           varrows = source.GroupBy(rowSelector.Compile())                            .Select(rowGroup => new                            {                                Key = rowGroup.Key,                                Values = columns.GroupJoin(                                    rowGroup,                                    c => c,                                    r => columnSelector(r),                                    (c, columnGroup) => dataSelector(columnGroup))                            }).ToArray();           foreach (varrow inrows)           {               varitems = row.Values.Cast<object>().ToList();               items.Insert(0, row.Key);               varobj = GetAnonymousObject(cols, items);               arr.Add(obj);                          }           returnarr.ToArray();       } privatestaticdynamic GetAnonymousObject(IEnumerable<string> columns, IEnumerable<object> values)       {           IDictionary<string, object> eo = newExpandoObject() as IDictionary<string, object>;           int i;           for(i = 0; i < columns.Count(); i++)           {               eo.Add(columns.ElementAt<string>(i), values.ElementAt<object>(i));           }           returneo;       } | 
ExpandoObject is used to create dynamic object.
Now, to convert row to column and get dynamic array:
Now, to convert row to column and get dynamic array:
| varpivotArray = data.ToPivotArray(                item => item.Year,               item => item.Product,               items => items.Any() ? items.Sum(x => x.Sales) : 0); | 
You can easily convert in JSON format
| String json = JsonConvert.SerializeObject(pivotArray, newKeyValuePairConverter()); | 
Here is the result:

C# DataTable to Pivot DataTable:
Let us have a DataTable with same data:
| DataTable myDataTable = newDataTable();myDataTable.Columns.AddRange(newDataColumn[3] { newDataColumn("Product"), newDataColumn("Year", typeof(int)), newDataColumn("Sales", typeof(int)) });myDataTable.Rows.Add("Product 1", 2009, 1212);myDataTable.Rows.Add("Product 2", 2009, 522);myDataTable.Rows.Add("Product 1", 2010, 1337);myDataTable.Rows.Add("Product 2", 2011, 711);myDataTable.Rows.Add("Product 2", 2012, 2245);myDataTable.Rows.Add("Product 3", 2012, 1000);    | 
You can use the same extension method to get Pivot DataTable like below.
| vardata2 = myDataTable.AsEnumerable().Select(x=> new{                Product =x.Field<String>("Product"),                Year= x.Field<int>("Year"),                Sales = x.Field<int>("Sales") });                     DataTable pivotDataTable =data2.ToPivotTable(                item => item.Year,               item => item.Product,               items => items.Any() ? items.Sum(x => x.Sales) : 0); | 
Here is the result:

DataTable to List<dynamic>:
If you need to convert DataTable to List of dynamic object then use following extension method:
| public staticList<dynamic> ToDynamicList(thisDataTable dt)       {           varlist = newList<dynamic>();           foreach (DataRow row indt.Rows)           {               dynamic dyn = newExpandoObject();               list.Add(dyn);               foreach (DataColumn column indt.Columns)               {                   vardic = (IDictionary<string, object>)dyn;                   dic[column.ColumnName] = row[column];               }           }           returnlist;       } | 
Here is the result:

Conclusion:
In this post, we played with C# Array, DataTable and implemented to convert row to column and get Pivot Array, DataTable and List of dynamic object.
Hope, It helps.
