1.DataTable数据去重
1 static void Main(string[] args) 2 { 3 DataTable dt = new DataTable();//创建表 4 DataColumn dc = null;//创建列 5 int fieldCount = 4;//列数 6 int rowCount = 4;//行数 7 //以下两个循环只是模拟向dt中添加数据 8 for (int i = 0; i < fieldCount; i++) 9 { 10 if (i==0) 11 { 12 dc = dt.Columns.Add("ID", Type.GetType("System.String")); 13 } 14 else 15 { 16 dc = dt.Columns.Add(string.Format("第{0}列", i.ToString()), Type.GetType("System.String")); 17 } 18 } 19 for (int i = 0; i < rowCount; i++) 20 { 21 DataRow newRow = dt.NewRow(); 22 for (int j = 0; j < fieldCount; j++) 23 { 24 if (j==0) 25 { 26 newRow["ID"] = Guid.NewGuid(); 27 } 28 else 29 { 30 newRow[string.Format("第{0}列", j.ToString())] = j; 31 } 32 } 33 dt.Rows.Add(newRow); 34 } 35 //数据去重处理 36 DataTable finalltable = dt.Clone(); 37 finalltable.Clear(); 38 var rows = from row in dt.AsEnumerable() 39 group row 40 by row["第1列"]//表示根据具体的哪一列进行去重 41 into myrow 42 select myrow.FirstOrDefault(); 43 foreach (DataRow row in rows) 44 { 45 finalltable.ImportRow(row); 46 } 47 }
模拟添加的数据:
数据去重后的结果:
2.DataTable排序
DataTable dtTop100Total = new DataTable(); DataRow[] rows = dtTop100Total.Select("", "int型的排序字段 DESC"); DataTable t = dtTop100Total.Clone(); t.Clear(); foreach (DataRow row in rows) { t.ImportRow(row); } dtTop100Total = t;
3.向DataTable中添加属于另一个DataTable的DataRow
DataTable dtSame = SQLHelper.ExecuteTableSQL(SqlQuery);//数据源 DataRow[] drSource = dtSame.Select(“过滤条件”, "排序字段 DESC/ASC"); DataTable dtTarget = dtSame.Clone();//复制数据源表结构 DataRow drTarget = dtTarget.NewRow();//创建新行 drTarget.ItemArray = drSource[0].ItemArray;//赋值 dtTarget.Rows.Add(drTarget);//添加
4.gridView绑定DataTable
DataTable dt = new DataTable(); dt.Columns.Add("htl_cd"); dt.Columns.Add("htl_nm"); Random r = new Random(); for (int i = 0; i < 100; i++) { DataRow dr = dt.NewRow(); dr[0] = r.Next(0, 1000); dr[1] = r.Next(0, 1000); dt.Rows.Add(dr); } this.gridControl1.DataSource = dt; this.gridView1.PopulateColumns(); //显示gridCOntrol 数据