1、用查询创建数据表
static void UseCopyToDataTable() { DataSet ds = BuildOneDTDataSet();//数据源 DataTable student = ds.Tables["PeopleDt"]; DataTable score = ds.Tables["Scores"]; var query = from stu in student.AsEnumerable() from sco in score.AsEnumerable() where stu.Field<int>("Age") > 20 && stu.Field<int>("ScoreID") == sco.Field<int>("ScoreID") select stu; foreach (var item in query) { Console.WriteLine("学生{0},年龄{1},性别{2}", item.Field<string>("Name"), item.Field<int>("Age"), item.Field<string>("XingBie")); } DataTable cnstudent = query.CopyToDataTable(); foreach (var item in cnstudent.AsEnumerable()) { Console.WriteLine("学生{0},年龄{1},性别{2}", item.Field<string>("Name"), item.Field<int>("Age"), item.Field<string>("XingBie")); } }
实际开发中CopyToDataTable通常用于界面绑定。
2、修改表中数据字段
static void UseSetField() { DataSet ds = BuildOneDTDataSet(); DataTable dt = ds.Tables["PeopleDt"]; foreach (var item in dt.AsEnumerable()) { int age=item.Field<int>("Age"); item.SetField<int>("Age",age+2); Console.WriteLine("学生{0},年龄{1},性别{2}", item.Field<string>("Name"), item.Field<int>("Age"), item.Field<string>("XingBie")); } DataTable dt2 = ds.Tables["PeopleDt"]; foreach (var item in dt2.AsEnumerable()) { Console.WriteLine("学生{0},年龄{1},性别{2}", item.Field<string>("Name"), item.Field<int>("Age"), item.Field<string>("XingBie")); } DataSet ds2 = BuildOneDTDataSet(); DataTable dt3 = ds2.Tables["PeopleDt"]; foreach (var item in dt3.AsEnumerable()) { Console.WriteLine("学生{0},年龄{1},性别{2}", item.Field<string>("Name"), item.Field<int>("Age"), item.Field<string>("XingBie")); } }
由此可见SetFiled()修改的是Dataset中的数据,如果要保持元数据不变,要么在SetFiled()之前先备份数据表使用CopyToDataTable(),要么另起一个DataSet 对象