问题描述
现在List<int[]>list=newList<int[]>且list有值,为了说的比较明白,现把每条值以下列方式显示出来:list[0][0]='a0'list[0][1]='a1'list[0][2]='a2'list[1][0]='b0'list[1][1]='b1'list[1][2]='b2'现要求转为DataTable型,显示如下:a0,a1,a2b0,b1,b2请各位大神指教!
解决方案
解决方案二:
双层for循环
解决方案三:
publicclassListToDataTable{publicstaticDataTableconvert2Table<Object>(List<Object>list){DataTabletable=newDataTable();if(list.Count>0){PropertyInfo[]properties=list[0].GetType().GetProperties();List<string>columns=newList<string>();foreach(PropertyInfopiinproperties){table.Columns.Add(pi.Name);columns.Add(pi.Name);}foreach(Objectiteminlist){object[]cells=getValues(columns,item);table.Rows.Add(cells);}}returntable;}privatestaticobject[]getValues(List<string>columns,objectinstance){object[]ret=newobject[columns.Count];for(intn=0;n<ret.Length;n++){PropertyInfopi=instance.GetType().GetProperty(columns[n]);objectvalue=pi.GetValue(instance,null);ret[n]=value;}returnret;}}
解决方案四:
///<summary>///将集合类转换成DataTable///</summary>///<paramname="list">集合</param>///<returns></returns>publicstaticDataTableToDataTable(IListlist){DataTableresult=newDataTable();if(list.Count>0){PropertyInfo[]propertys=list[0].GetType().GetProperties();foreach(PropertyInfopiinpropertys){result.Columns.Add(pi.Name,pi.PropertyType);}for(inti=0;i<list.Count;i++){ArrayListtempList=newArrayList();foreach(PropertyInfopiinpropertys){objectobj=pi.GetValue(list[i],null);tempList.Add(obj);}object[]array=tempList.ToArray();result.LoadDataRow(array,true);}}returnresult;}///<summary>///将泛型集合类转换成DataTable///</summary>///<typeparamname="T">集合项类型</typeparam>///<paramname="list">集合</param>///<returns>数据集(表)</returns>publicstaticDataTableToDataTable<T>(IList<T>list){returnConvertX.ToDataTable<T>(list,null);}///<summary>///将泛型集合类转换成DataTable///</summary>///<typeparamname="T">集合项类型</typeparam>///<paramname="list">集合</param>///<paramname="propertyName">需要返回的列的列名</param>///<returns>数据集(表)</returns>publicstaticDataTableToDataTable<T>(IList<T>list,paramsstring[]propertyName){List<string>propertyNameList=newList<string>();if(propertyName!=null)propertyNameList.AddRange(propertyName);DataTableresult=newDataTable();if(list.Count>0){PropertyInfo[]propertys=list[0].GetType().GetProperties();foreach(PropertyInfopiinpropertys){if(propertyNameList.Count==0){result.Columns.Add(pi.Name,pi.PropertyType);}else{if(propertyNameList.Contains(pi.Name))result.Columns.Add(pi.Name,pi.PropertyType);}}for(inti=0;i<list.Count;i++){ArrayListtempList=newArrayList();foreach(PropertyInfopiinpropertys){if(propertyNameList.Count==0){objectobj=pi.GetValue(list[i],null);tempList.Add(obj);}else{if(propertyNameList.Contains(pi.Name)){objectobj=pi.GetValue(list[i],null);tempList.Add(obj);}}}object[]array=tempList.ToArray();result.LoadDataRow(array,true);}}returnresult;}
解决方案五:
该回复于2012-01-12 15:54:56被版主删除
解决方案六:
引用3楼fengyarongaa的回复:
C#code///<summary>///将集合类转换成DataTable///</summary>///<paramname="list">集合</param>///<returns></returns>publicstaticDataTableToDataTable(IList……
给力
解决方案七:
各位都亲自测试过吗?