• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Dreama
只想要简简单单的快乐!
博客园    首页    新随笔    联系   管理     

DataTable 与ToList<T>互转

DataDable -> ToList<T>

public static List<T> ToList<T>(this DataTable dt)
        {
            var dataColumn = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName).ToList();

            var properties = typeof(T).GetProperties();
            string columnName = string.Empty;

            return dt.AsEnumerable().Select(row =>
            {
                var t = Activator.CreateInstance<T>();
                foreach (var p in properties)
                {
                    columnName = p.Name;
                    if (dataColumn.Contains(columnName))
                    {
                        if (!p.CanWrite)
                            continue;

                        object value = row[columnName];
                        Type type = p.PropertyType;

                        if (value != DBNull.Value)
                        {
                            p.SetValue(t, Convert.ChangeType(value, type), null);
                        }
                    }
                }
                return t;
            }).ToList();
        }

ToList<T> ->  DataDable 

public static DataTable ToDataTable<T>(this List<T> items)
        {
            DataTable dataTable = new DataTable();

            PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo prop in Props)
            {
                dataTable.Columns.Add(prop.Name,prop.PropertyType);
            }

            foreach (T obj in items)
            {
                var values = new object[Props.Length];
                for (int i = 0; i < Props.Length; i++)
                {
                    values[i] = Props[i].GetValue(obj, null);
                }
                dataTable.Rows.Add(values);
            }

            return dataTable;
        }

 

posted on 2017-12-18 20:48  Dreamma  阅读(2487)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3

© 本文章版权归 Dreama 所有, 转载授权请联系: cnxy@88.com

如果本文对您有帮助,欢迎支持原创

支付宝

支付宝扫码支持

微信

微信赞赏支持