C# 利用反射把DataTable转为List
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;
using System.ComponentModel;
namespace SM.RoadConditionFileManagment.Helper
{
public class ModelConvertHelper
{
/// <summary>
/// DataTable转为List
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns>List</returns>
public static List<T> TableToList<T>(DataTable dt) where T : new()
{
List<T> list = new List<T>();
Type type = typeof(T);
foreach (DataRow row in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
// 检查DataTable是否包含此列
if (dt.Columns.Contains(pi.Name))
{
// 判断此属性是否有Setter
if (!pi.CanWrite)
continue;
object value = row[pi.Name];
if (value != DBNull.Value)
{
//获取此字段的类型
Type typePi = pi.PropertyType;
TypeCode typeCodePi = new TypeCode();
//判断此字段是否为nullable泛型类
//如果是就利用NullableConverter类获取其基本类型
//如果不是就直接获取其基本类型
if (typePi.IsGenericType && typePi.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
NullableConverter nullableConverter = new NullableConverter(typePi);
Type type1 = nullableConverter.UnderlyingType;
typeCodePi = Type.GetTypeCode(type1);
}
else
{
typeCodePi = Type.GetTypeCode(typePi);
}
//转换数据类型
switch (typeCodePi)
{
case TypeCode.DateTime:
pi.SetValue(t, Convert.ToDateTime(value), null);
break;
case TypeCode.Double:
pi.SetValue(t, Convert.ToDouble(value), null);
break;
case TypeCode.Empty:
pi.SetValue(t, "", null);
break;
case TypeCode.Int32:
pi.SetValue(t, Convert.ToInt32(value), null);
break;
case TypeCode.Object:
pi.SetValue(t, value, null);
break;
case TypeCode.String:
pi.SetValue(t, Convert.ToString(value), null);
break;
default:
break;
}
}
}
}
list.Add(t);
}
return list;
}
}
}