DataTable与数组相互转换
|
using System; using System.Data; using System.Data.OleDb; namespace pxkt_datatable { class pxkt { public pxkt() { string[] g = new string[10]; for(int i=0;i<10;i++) { g[i]=i.ToString(); } // 数组 转 数据表DataTable DataTable dt = new DataTable(); dt.Columns.Add("name",typeof(string)); for (int k=0;k<g.Length;k++) { DataRow dr = dt.NewRow(); dr["name"]=g[k]; dt.Rows.Add(dr); } //输出数据表 Console.WriteLine("打出数据表!"); for(int j= 0;j<dt.Rows.Count;j++) { DataRow dr1 = dt.Rows[j]; Console.WriteLine(dr1["name"].ToString()); }
//数据表DataTable转数组 string[] arrayA = new string[dt.Rows.Count]; for(int x=0;x<dt.Rows.Count;x++) { DataRow dr2 = dt.Rows[x]; arrayA[x]=Convert.ToString(dr2["name"]); } //输出数组 Console.WriteLine("打出数组!"); for(int y=0;y<arrayA.Length;y++) { Console.WriteLine(arrayA[y]); } foreach(string printarray in arrayA) { Console.WriteLine(printarray); } } static pxkt() {
} } class test { static void Main() { pxkt p = new pxkt(); } } } 来自:http://www.cnblogs.com/peirunou/archive/2008/12/04/1347753.html DataTable转数组
来自:http://hi.baidu.com/qingcaodeng13/blog/item/633eb20941f8a5a92fddd4c2.html int row=DataTable1.Rows.Count; int col=DataTable1.Columns.Count; int[,] tb=new int[row,col]; for(int r=0;r<row;r++) { for(int c=0;c<col;c++) { tb[r,c]=int.Parse(DataTable1.Rows[r][c].ToString()); } } DataTable1是DataTable的一个实例,tb为所得的二维数组 来自:http://zhidao.baidu.com/question/32876214.html 在最近做的一个案子里,需要绑定实体数组比如Materiel[]绑定到界面(winform/webform都有),虽然可以直接绑定数组到GridView,但排序,过滤,查找等操作在数组里不是很方便。所以想借用DataTable做数据源。 最简单的方法就是手动建一个DataTable。为每个Materiel的property建一个Column,然后指明其数据类型。建好Table之后,循环为每个Materiel创建一个新行。如果多有几个界面,虽然做起来都差不多,但代码很难重用。 另外数据都是从WebService获取,form不允许直接访问DB,所以也不能通过ADO.net获取DataTable。 经过一段时间的考量后决定见一个专用的Utility类EntityCollectionsConvert,接口为
DataTable ToDataTable(object[] entitys); DataTable ToDataTable<T>(List<T> entitys) 实现的原理也比较简单 1.将判断entitys不为空; 2.取出entitys的所有property 3.在DataTable中为每个property添加一列(包括元素类型) 4.为每个entity添加一行。 5.自动生成单元测试,测试,添加到项目中
view plaincopy to clipboardprint?
|
浙公网安备 33010602011771号