C# List<T>转成DataTable
//将List<T>转成DataTable
public static DataTable ToDataTable(List<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > 0)
{
for (int i = 0; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}
public static class Extension
{
public static DataTable ListToDataTable<T>(this IList<T> data, string tableName)
{
DataTable table = new DataTable(tableName); //special handling for value types and string
if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
{ DataColumn dc = new DataColumn("Value");
table.Columns.Add(dc);
foreach (T item in data)
{
DataRow dr = table.NewRow();
dr[0] = item;
table.Rows.Add(dr);
}
}
else
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in properties)
{
table.Columns.Add(prop.Name,
Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
try
{
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
}
catch (Exception ex)
{
row[prop.Name] = DBNull.Value;
}
}
table.Rows.Add(row);
}
}
return table;
}
}
最新文章
- Lambda 表达式递归用法实例
- Node.js与Sails~项目结构与Mvc实现
- hdu1026.Ignatius and the Princess I(bfs + 优先队列)
- Linq之Expression进阶
- HDOJ 1075
- [收藏夹整理]OpenCV部分
- OD调试程序3
- 【转】 远程到服务器安装visualSVN server,出现Service &#39;VisualSVN Server&#39; failed to start的解决方法
- aliyun install php apache mysql nginx
- 水王ID查找
- sql只修改第一二行数据
- Android实现多页左右滑动效果,支持子view动态创建和cache
- 1493: [NOI2007]项链工厂
- AVAudioPlayer 播放音频
- Apache+Tomcat实现动静分离
- logstash处理文件进度记录机制
- servlet篇 之 servlet的访问
- python requests的content和text方法的区别
- Android style 继承
- Qt编写自定义控件9-导航按钮控件
热门文章
- 我的C++笔记(数据的共享与保护)
- (转)Openlayers 2.X加载天地图
- springboot 多数据源的实现
- Laravel -- windows apache .htaccess https 路由重写
- [转载]Linux内存高,触发oom-killer问题解决
- Xcache3.2.0不支持php7.0.11
- 三剑客基础详解(grep、sed、awk)
- BZOJ 1396 识别子串 (后缀自动机、线段树)
- cxdbtreelist的按记录查找节点
- 2018ICPC南京