<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LinqDemo2.aspx.cs" Inherits="LinqDemo2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>LinQ实现DataTable不定行转列</title> </head> <body> <form id="form1" runat="server"> <div> 原始表:<br /> <asp:GridView ID="GridView1" runat="server" Width="300px"> </asp:GridView> <br /> 转换以后的表:<br /> <asp:GridView ID="GridView2" runat="server" Width="300px"> </asp:GridView> </div> </form> </body> </html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Web.UI; using System.Web.UI.WebControls; public partial class LinqDemo2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { #region 添加一个表 DataTable _dt = new DataTable(); _dt.Columns.Add(new DataColumn("ID", typeof(int)) { DefaultValue = 0 }); _dt.Columns.Add(new DataColumn("Name", typeof(string)) { DefaultValue = "1" }); _dt.Columns.Add(new DataColumn("Item", typeof(string)) { DefaultValue = "1" }); _dt.Columns.Add(new DataColumn("ItemAmount", typeof(double)) { DefaultValue = 0 }); _dt.Rows.Add(1, "小李", "零点提成", 60); _dt.Rows.Add(1, "小李", "订房提成", 70); _dt.Rows.Add(2, "小张", "零点提成", 500); _dt.Rows.Add(2, "小张", "订房提成", 60); _dt.Rows.Add(2, "小张", "订单提成", 800); _dt.Rows.Add(3, "小王", "零点提成", 30); _dt.Rows.Add(3, "小王", "订单提成", 900); #endregion GridView1.DataSource = _dt; GridView1.DataBind(); GridView2.DataSource = ConvertToTable(_dt); GridView2.DataBind(); } #region 转换表 static DataTable ConvertToTable(DataTable source) { DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("Name"); var columns = (from x in source.Rows.Cast<DataRow>() select x[2].ToString()).Distinct(); foreach (var item in columns) dt.Columns.Add(item).DefaultValue = 0; var data = from x in source.Rows.Cast<DataRow>() group x by x[1] into g select new { Key = g.Key.ToString(), Items = g }; data.ToList().ForEach(x => { string[] array = new string[dt.Columns.Count]; array[1] = x.Key; for (int i = 2; i < dt.Columns.Count; i++) { if (array[0] == null) array[0] = x.Items.ToList<DataRow>()[0]["ID"].ToString(); array[i] = (from y in x.Items where y[2].ToString() == dt.Columns[i].ToString() select y[3].ToString() ).SingleOrDefault(); } dt.Rows.Add(array); }); return dt; } #endregion }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80