zoukankan      html  css  js  c++  java
  • 可用的datatable转换成List<T>

    public static class ConvertHelper
    {
    public static List<T> ToDataList<T>(this DataTable dt)
    {
    var list = new List<T>();
    var plist = new List<PropertyInfo>(typeof(T).GetProperties());
    foreach(DataRow item in dt.Rows)
    {
    T s = Activator.CreateInstance<T>();
    for(int i = 0; i < dt.Columns.Count; i++)
    {
    PropertyInfo info = plist.Find(p => p.Name == dt.Columns[i].ColumnName);
    if(info != null)
    {
    try
    {
    if(!Convert.IsDBNull(item[i]))
    {
    object v = null;
    if(info.PropertyType.ToString().Contains("System.Nullable"))
    {
    v = Convert.ChangeType(item[i], Nullable.GetUnderlyingType(info.PropertyType));
    }
    else
    {
    v = Convert.ChangeType(item[i], info.PropertyType);
    }
    info.SetValue(s, v, null);
    }
    }
    catch(Exception ex)
    {
    throw new Exception("字段[" + info.Name + "]转换出错," + ex.Message);
    }
    }
    }
    list.Add(s);
    }
    return list;
    }
    }

  • 相关阅读:
    Shell脚本sed命令
    Shell脚本常用unix命令
    Shell的case语句
    3.5.2 数值之间的转换
    3.5.1 数学函数与常量
    3.5 运算符
    3.4.2 常量
    3.4.1 变量初始化
    3.4 变量
    Python异常捕捉的一个小问题
  • 原文地址:https://www.cnblogs.com/chengyihardworking/p/12937116.html
Copyright © 2011-2022 走看看