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:
var data = 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 static DataTable ToPivotTable<T, TColumn, TRow, TData>(
this IEnumerable<T> source,
Func<T, TColumn> columnSelector,
Expression<Func<T, TRow>> rowSelector,
Func<IEnumerable<T>, TData> dataSelector)
{
DataTable table = new DataTable();
v

本文介绍如何使用C#及LINQ将数组或DataTable中的行转换为列,实现数据的转置与数据透视功能,并提供两种实现方式:生成DataTable和动态数组,适用于Web API返回JSON数据。
&spm=1001.2101.3001.5002&articleId=116556111&d=1&t=3&u=aa5a174d1f9d466b9d15131032f92b8a)
7558

被折叠的 条评论
为什么被折叠?



