DataTable 转 List<T>

csharp

浏览数:501

2019-1-7

AD:资源代下载服务


ConvertTo

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;       

namespace Ldh.Utils
{
    public class Helper
    {
        /// <summary>
        /// 将 DataTable 转换为 IList<T>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt">数据源表</param>
        /// <returns></returns>
        public List<T> ConvertTo<T>(DataTable dt) where T : new()
        {
            if (null == dt || 0 == dt.Rows.Count)
            {
                return null;
            }
            Type type = typeof(T);
            if (null == type || type.IsValueType)
            {
                return null;
            }
            List<T> result = new List<T>(dt.Rows.Count);
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public);
            DataRowCollection rows = dt.Rows;
            DataColumnCollection columns = dt.Columns;
            foreach (DataRow dr in rows)
            {
                T obj = new T();
                //T obj = Activator.CreateInstance<T>();
                //T obj = Activator.CreateInstance(T);
                foreach (PropertyInfo pi in properties)
                {
                    string name = pi.Name.ToLower();
                    if (columns.Contains(name) && pi.CanWrite)
                    {
                        string value = dr[name].ToString();
                        if (!pi.PropertyType.IsGenericType)
                        {
                            //非泛型
                            pi.SetValue(obj, (string.IsNullOrEmpty(value)) ? null : Convert.ChangeType(value, pi.PropertyType), null);
                        }
                        else
                        {
                            //泛型Nullable<>
                            Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
                            if (genericTypeDefinition == typeof(Nullable<>))
                            {
                                pi.SetValue(obj, string.IsNullOrEmpty(value) ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(pi.PropertyType)), null);
                            }
                        }
                    }
                }
                result.Add(obj);
            }
            return result;
        }
    }
}