//将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;
}
}

  

最新文章

  1. Lambda 表达式递归用法实例
  2. Node.js与Sails~项目结构与Mvc实现
  3. hdu1026.Ignatius and the Princess I(bfs + 优先队列)
  4. Linq之Expression进阶
  5. HDOJ 1075
  6. [收藏夹整理]OpenCV部分
  7. OD调试程序3
  8. 【转】 远程到服务器安装visualSVN server,出现Service &#39;VisualSVN Server&#39; failed to start的解决方法
  9. aliyun install php apache mysql nginx
  10. 水王ID查找
  11. sql只修改第一二行数据
  12. Android实现多页左右滑动效果,支持子view动态创建和cache
  13. 1493: [NOI2007]项链工厂
  14. AVAudioPlayer 播放音频
  15. Apache+Tomcat实现动静分离
  16. logstash处理文件进度记录机制
  17. servlet篇 之 servlet的访问
  18. python requests的content和text方法的区别
  19. Android style 继承
  20. Qt编写自定义控件9-导航按钮控件

热门文章

  1. 我的C++笔记(数据的共享与保护)
  2. (转)Openlayers 2.X加载天地图
  3. springboot 多数据源的实现
  4. Laravel -- windows apache .htaccess https 路由重写
  5. [转载]Linux内存高,触发oom-killer问题解决
  6. Xcache3.2.0不支持php7.0.11
  7. 三剑客基础详解(grep、sed、awk)
  8. BZOJ 1396 识别子串 (后缀自动机、线段树)
  9. cxdbtreelist的按记录查找节点
  10. 2018ICPC南京