C#使用反射将DataTable转换List<T>

来源:互联网 发布:网络上的uv是什么意思 编辑:程序博客网 时间:2024/06/10 00:40

直接上干货

/// <summary>    /// DataTable转换为List    /// </summary>    public static class ToList    {        public static IList<T> ToLists<T>(this DataTable table)        {            if (table == null)            {                return null;            }            List<DataRow> rows = new List<DataRow>();            foreach (DataRow row in table.Rows)            {                rows.Add(row);            }            return ConvertTo<T>(rows);          }        public static IList<T> ConvertTo<T>(IList<DataRow> rows)        {            IList<T> list = null;            if (rows != null)            {                list = new List<T>();                foreach (DataRow row in rows)                {                    T item = CreateItem<T>(row);                    list.Add(item);                }            }            return list;        }        public static T CreateItem<T>(DataRow row)        {            T obj = default(T);            if (row != null)            {                obj = Activator.CreateInstance<T>();                foreach (DataColumn column in row.Table.Columns)                {                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);                    try                    {                        object value = row[column.ColumnName];                        prop.SetValue(obj, value, null);                    }                    catch                    {  //You can log something here                             //throw;                        }                }            }            return obj;        }
0 0