DataTable 操作集合
#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();
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();
}
}
}