DataTable|DataTable 行转列
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("code");
dt.Columns.Add("amount");
dt.Rows.Add("m1", "cash", "90");
dt.Rows.Add("m1", "nets", "50");
dt.Rows.Add("m2", "cash", "190");
dt.Rows.Add("m2", "nets", "150");
dt.Rows.Add("m2", "another", "222");
dt.Rows.Add("m3", "cash", "150");
dt.Rows.Add("m3", "another", "100");
Console.WriteLine("Source:");
DisplayTable(dt);
Console.WriteLine("Target:");
DisplayTable(ConvertDataTable(dt));
}static DataTable ConvertDataTable(DataTable source)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
var columns = (from x in source.Rows.Cast() select x[1].ToString()).Distinct();
foreach (var item in columns) dt.Columns.Add(item);
var data = https://www.it610.com/article/from x in source.Rows.Cast()
group x by x[0] into g
select new { Key = g.Key.ToString(), Items = g };
data.ToList().ForEach(x =>
{
string[] array = new string[dt.Columns.Count];
array[0] = x.Key;
for (int i = 1;
i < dt.Columns.Count;
i++)
array[i] = (from y in x.Items
where y[1].ToString() == dt.Columns[i].ToString()
select y[2].ToString())
.SingleOrDefault();
dt.Rows.Add(array);
});
return dt;
}static void DisplayTable(DataTable dt)
{
dt.Columns.Cast().ToList().ForEach(x => Console.Write(x + "\t"));
Console.WriteLine();
dt.Rows.Cast().ToList().ForEach(x =>
{
x.ItemArray.ToList().ForEach(y => Console.Write(y.ToString() + "\t"));
Console.WriteLine();
});
}
}
}
【DataTable|DataTable 行转列】
Source:
idcodeamount
m1cash90
m1nets50
m2cash190
m2nets150
m2another 222
m3cash150
m3another 100
Target:
idcashnetsanother
m19050
m2190150222
m3150100
Press any key to continue . . .
推荐阅读
- 数据库|SQL行转列方式优化查询性能实践
- windows进程共享内存技术
- 校门外的树 线段树版
- 2018-11-14作业1
- Scripting the Editor using Python
- 利用SSIS更新SSAS多维数据集
- hdu|hdu 5528
- 通过代码方式操作IIS7
- PAT|Heaps
- C#-使用哈希表对XML进行查询