zoukankan      html  css  js  c++  java
  • 通过反射和泛型实现DataTable转Object

    实现DataTable转为对象
    /// <summary>
            /// 转换DataTable为指定类型的list对象
            /// </summary>
            /// <typeparam name="T">指定的转换类型</typeparam>
            /// <param name="dt">需要转换的DataTable</param>
            /// <returns></returns>
            public static List<T> DataTableToList<T>(DataTable dt) where T : class, new()
            {
                var list = new List<T>();
                if (dt.Rows.Count > 0)
                {
                    var propertyInfoes = typeof(T).GetProperties();
                    foreach (DataRow dataRow in dt.Rows)
                    {
                        var t = new T();
                        foreach (var propertyInfo in propertyInfoes)
                        {
                            var tempName = propertyInfo.Name;
                            if (dt.Columns.Contains(tempName))
                            {
                                if (!propertyInfo.CanWrite) continue;
                                object value = dataRow[tempName];
                                if (value != DBNull.Value)
                                {
                                    propertyInfo.SetValue(t, value);
                                }
                            }
                        }
                        list.Add(t);
                    }
                }
    
                return list;
            }
    
            public static T DataTableToModel<T>(DataTable dt) where T : class, new()
            {
                if (dt.Rows.Count <= 0)
                {
                    return default(T);
                }
                else
                {
                    var t = new T();
                    var propertyInfoes = typeof(T).GetProperties();
                    foreach (var propertyInfo in propertyInfoes)
                    {
                        var tempName = propertyInfo.Name;
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!propertyInfo.CanWrite) continue;
                            object value = dt.Rows[0][tempName];
                            if (value != DBNull.Value)
                            {
                                propertyInfo.SetValue(t, value);
                            }
                        }
                    }
    
                    return t;
                }
            }
        }
    
  • 相关阅读:
    C++中的类访问控制
    Docker应用程序容器技术_转
    16C554(8250)驱动分析
    动态调频DVFS_转
    ubifs概述
    ubifs物理存储
    fmt-重新格式化段落
    uniq-删除重复
    sort
    join用法
  • 原文地址:https://www.cnblogs.com/prayol/p/8507961.html
Copyright © 2011-2022 走看看