zoukankan      html  css  js  c++  java
  • C#DataTable转List<Models>

    调用:

    List<BASEINFO> mar = DataTableToIList<BASEINFO>(myData.Tables[0]).ToList<BASEINFO>();
    DataTableToIList方法:
     /// <summary>
            /// DataTable转为List<T>
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="table"></param>
            /// <returns></returns>
            public static IList<T> DataTableToIList<T>(DataTable table)
            {
                IList<T> result = new List<T>();
    
                for (int j = 0; j < table.Rows.Count; j++)
                {
                    T _t = (T)Activator.CreateInstance(typeof(T));
                    PropertyInfo[] propertys = _t.GetType().GetProperties();
    
                    foreach (PropertyInfo p in propertys)
                    {
                        if (!table.Columns.Contains(p.Name)) continue;
                        if (string.IsNullOrEmpty(table.Rows[j][p.Name].ToString())) continue;
                        //Type t = p.PropertyType;
                        //MethodInfo m = t.GetMethod("TryParse");
                        switch (p.PropertyType.Name)
                        {
                            case "Int32":
                                p.SetValue(_t, Int32.Parse(table.Rows[j][p.Name].ToString()));
                                break;
                            case "Int64":
                                p.SetValue(_t, Int64.Parse(table.Rows[j][p.Name].ToString()));
                                break;
                            case "Decimal":
                                p.SetValue(_t, Decimal.Parse(table.Rows[j][p.Name].ToString()));
                                break;
                            case "Double":
                                p.SetValue(_t, Double.Parse(table.Rows[j][p.Name].ToString()));
                                break;
                            case "DateTime":
                                p.SetValue(_t, DateTime.Parse(table.Rows[j][p.Name].ToString()));
                                break;
                            default:
                                p.SetValue(_t, table.Rows[j][p.Name].ToString());
                                break;
                        }
    
                    }
                    result.Add(_t);
                }
    
                return result;
            }
  • 相关阅读:
    负外边距--转载
    研究Dropbox Server端文件系统
    Bluetooth Profile for iPhone from the functional perspectives
    Somebody That I Used to Know
    复合查询
    聚合查询
    Filter查询
    ES基本查询
    ES版本控制
    ES基本操作
  • 原文地址:https://www.cnblogs.com/wangjp-1233/p/13281171.html
Copyright © 2011-2022 走看看