博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
支持库:DataTable扩展ToList方法
阅读量:4577 次
发布时间:2019-06-08

本文共 3037 字,大约阅读时间需要 10 分钟。

public static class DataTableExtensions    {        public static List
ToList
(this DataTable dt) where T : new() { var list = new List
(); if (dt == null) return list; var len = dt.Rows.Count; for (var i = 0; i < len; i++) { var info = new T(); foreach (DataColumn dc in dt.Rows[i].Table.Columns) { var field = dc.ColumnName; var value = dt.Rows[i][field].ToString(); if (string.IsNullOrEmpty(value)) continue; if (IsDate(value)) { value = DateTime.Parse(value).ToString(); } var p = info.GetType().GetProperty(field); try { if (p.PropertyType == typeof(string)) { p.SetValue(info, value, null); } else if (p.PropertyType == typeof(int)) { p.SetValue(info, int.Parse(value), null); } else if (p.PropertyType == typeof(bool)) { p.SetValue(info, bool.Parse(value), null); } else if (p.PropertyType == typeof(DateTime)) { p.SetValue(info, DateTime.Parse(value), null); } else if (p.PropertyType == typeof(float)) { p.SetValue(info, float.Parse(value), null); } else if (p.PropertyType == typeof(double)) { p.SetValue(info, double.Parse(value), null); } else { p.SetValue(info, value, null); } } catch (Exception) { //p.SetValue(info, ex.Message, null); } } list.Add(info); } dt.Dispose(); dt = null; return list; } ///
/// 按照属性顺序的列名集合 /// public static IList
GetColumnNames(this DataTable dt) { DataColumnCollection dcc = dt.Columns; //由于集合中的元素是确定的,所以可以指定元素的个数,系统就不会分配多余的空间,效率会高点 IList
list = new List
(dcc.Count); foreach (DataColumn dc in dcc) { list.Add(dc.ColumnName); } return list; } private static bool IsDate(string d) { DateTime d1; double d2; return !double.TryParse(d, out d2) && DateTime.TryParse(d, out d1); } }

  

转载于:https://www.cnblogs.com/blackice/archive/2013/01/09/2852596.html

你可能感兴趣的文章
Android之内存泄露
查看>>
前端验证 validform
查看>>
分布式计算
查看>>
《debug unreal engine code》
查看>>
RocketMQ之双Master方式部署以及简单使用
查看>>
现身说法:面对DDoS攻击时该如何防御?
查看>>
C的动态链表建立
查看>>
source insight 不能添加cc文件
查看>>
NYOJ 16 矩形嵌套
查看>>
Leetcode中的SQL题目练习(二)
查看>>
dubbo 集群容错源码
查看>>
Collection接口的子接口——Queue接口
查看>>
LINUX安装NGINX
查看>>
服务器启动项目抛错 没有到主机的路由
查看>>
python_85_sys模块
查看>>
第九周动手动脑
查看>>
HDU 1811 Rank of Tetris
查看>>
网站UI分析
查看>>
winform 获取当前名称
查看>>
报表分栏后的排序
查看>>