zoukankan      html  css  js  c++  java
  • DataTable或者DataRow转换对象

     public static IEnumerable<T> ConvertObject<T>(DataTable dt) where T : new()
            {
    
                var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                List<PropertyInfo> Fields = new List<PropertyInfo>();
                foreach (var s in v)
                {
                    if (dt.Columns.Contains(s.Name))
                        Fields.Add(s);
                }
    
                foreach (DataRow dr in dt.Rows)
                {
                    T t = new T();
                    foreach (var s in Fields)
                    {
                        if (object.Equals(dr[s.Name], DBNull.Value)) continue;
                        s.SetValue(t, dr[s.Name], null);
                    }
                    yield return t;
                }
            }
    
            public static T ConvertObject<T>(DataRow dr) where T : new()
            {
    
                var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    
                T t = new T();
                foreach (var s in v)
                {
                    if (dr.Table.Columns.Contains(s.Name))
                    {
                        s.SetValue(t, dr[s.Name], null);
                    }
    
                }
    
                return t;
    
            }

    Bug,

    1.如果泛型对象(T)属性的类型和DataTable列的类型不一致,抛异常  ---懒得解决

    2.DBNull.value转换失败,新方法

      public static T ConvertObject<T>(DataRow dr) where T : new()
            {
    
                var v = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
    
                T t = new T();
                foreach (var s in v)
                {
                    if (dr.Table.Columns.Contains(s.Name))
                    {
                        if (object.Equals(dr[s.Name], DBNull.Value)) continue;
                        {
                            s.SetValue(t, dr[s.Name]);
                        }
                    }
    
                }
    
                return t;
    
            }
    慎于行,敏于思!GGGGGG
  • 相关阅读:
    入门菜鸟
    FZU 1202
    XMU 1246
    Codeforces 294E Shaass the Great 树形dp
    Codeforces 773D Perishable Roads 最短路 (看题解)
    Codeforces 814E An unavoidable detour for home dp
    Codeforces 567E President and Roads 最短路 + tarjan求桥
    Codeforces 567F Mausoleum dp
    Codeforces 908G New Year and Original Order 数位dp
    Codeforces 813D Two Melodies dp
  • 原文地址:https://www.cnblogs.com/GarsonZhang/p/5291931.html
Copyright © 2011-2022 走看看