#region 根据datatable获得列名 public static string[] GetColumnsByDataTable(DataTable dt) /// <summary> /// 根据datatable获得列名 /// </summary> /// <param name="dt">表对象</param> /// <returns>返回结果的数据列数组</returns> public static string[] GetColumnsByDataTable(DataTable dt) { string[] strColumns = null; if (dt.Columns.Count > 0) { int columnNum = 0; columnNum = dt.Columns.Count; strColumns = new string[columnNum]; for (int i = 0; i < dt.Columns.Count; i++) { strColumns[i] = dt.Columns[i].ColumnName; } } return strColumns; } #endregion
把datatable的结构全部数据或部分数据复制到一个新的datatable
datatable复制表结构:我们可以使用.clone()方法;
DataTable oldDT = GetDataTable();
DataTable newDT = oldDT.Clone();
把datatable中的所有信息复制到一个新的datatable,包括结构和数据:
DataTable oldDT = GetDataTable();
DataTable newDT = oldDT.Copy();
复制datatable中的某一行:我们可以使用.ImportRow()方法;
DataTable oldDT = GetDataTable();
DataTable newDT = new DataTable();
newDT.ImportRow(oldDT.Rows[1]);把原来datatable中的第二行数据复制到新的datatable中。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTableGroupDemo
{
class Program
{
static void Main(string[] args)
{
// 准备数据
DataTable dt = new DataTable();
// 创建列
DataColumn dcName = new DataColumn("Name", typeof(string));
DataColumn dcAge = new DataColumn("Age", typeof(Int32));
DataColumn dcScore = new DataColumn("Score", typeof(Int32));
// 添加列
dt.Columns.Add(dcName);
dt.Columns.Add(dcAge);
dt.Columns.Add(dcScore);
// 添加数据
dt.Rows.Add(new object[] { "Tom", 23, 67 });
dt.Rows.Add(new object[] { "Tom", 23, 67 });
dt.Rows.Add(new object[] { "Jack", 21, 100 });
dt.Rows.Add(new object[] { "Greey", 24, 56 });
dt.Rows.Add(new object[] { "Kevin", 24, 77 });
dt.Rows.Add(new object[] { "Tom", 23, 82 });
dt.Rows.Add(new object[] { "Greey", 24, 80 });
dt.Rows.Add(new object[] { "Jack", 21, 90 });
#region 使用Linq expression to DataTable group by
var query = from p in dt.AsEnumerable()
group p by new { name = p.Field<string>("Name"),score=p.Field<Int32>("Score") } into m
select new
{
Name = m.Key.name,
Score=m.Key.score
};
#endregion
// 输出
Console.WriteLine("Linq");
foreach (var item in query)
{
Console.WriteLine(item);
}
Console.WriteLine("GroupBy");
IEnumerable<IGrouping<string, DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(dr => dr["Name"].ToString());
foreach (IGrouping<string, DataRow> ig in result)
{
Console.WriteLine("key=" + ig.Key + ":");
foreach (DataRow dr in ig)
{
Console.WriteLine(dr["Name"].ToString().PadRight(10) + dr["Age"].ToString().PadRight(10) + dr["Score"].ToString().PadRight(10));
}
}
Console.ReadKey();
}
}
}