1.DataTable合并
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15// 一般方法,性能不好 DataTable[] srcTables = ... ; foreach( DataTable src in srcTables ) { dest.Merge( src ) ; } // 推荐方法,速度是上面的100倍 DataTable[] srcTables = ... ; foreach( DataTable src in srcTables ) { foreach( DataRow row in src.Rows) { dest.ImportRow( row ) ; } }
2.DataTable过滤
复制代码
1
2
3
4
5
6
7
8
9
10// 一般方法,性能不好 DataView dv = dt.DefaultView ; dv.RowFilter = filter ; DataTable result = dv.ToTable() ; // 推荐方法,有数十倍的性能提高。 DataRow[] rows = dv.Select( filter ) ; foreach( DataRow row in rows ) { result.ImportRow(row) ; }
3.DataTableReader使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12using (DataTableReader dr = dt.CreateDataReader()) { while (dr.Read()) { int len = dr.FieldCount; for (int i = 0; i < len; i++) { System.Console.Write("{0}t,", dr.GetValue(i)); } System.Console.WriteLine(); } }
3.DataTable与XML相互转换
复制代码
1
2
3
4
5
6
7//DataTable写入到XML dt.WriteXmlSchema("xmlSchema文件路径"); dt.WriteXml("xml文件路径"); //读取XML文件内容到DataTable DataTable table = new DataTable(); table.ReadXmlSchema("xmlSchema文件路径"); table.ReadXml("xml文件路径");
4.DataTable 间创建 Relation
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20private void MakeDataTableRelation() { DataTable student = new DataTable(); student.Columns.Add("ID", typeof(int)); student.Columns.Add("Name", typeof(string)); student.Rows.Add(1, "张三"); student.Rows.Add(2, "李四"); student.Rows.Add(3, "王五"); DataTable score = new DataTable(); score.Columns.Add("ID", typeof(int)); score.Columns.Add("Score", typeof(int)); score.Rows.Add(1, 50); score.Rows.Add(2, 60); score.Rows.Add(3, 70); // student,score必须放到DataSet中才能创建DataRelation DataSet ds = new DataSet(); ds.Tables.AddRange(new DataTable[] { student, score }); DataRelation relation = new DataRelation("stu_score", student.Columns[0], score.Columns[0]); student.ChildRelations.Add(relation); }
最后
以上就是奋斗摩托最近收集整理的关于C# DataTable使用方法详解(二)的全部内容,更多相关C#内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复