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
  • 相关阅读:
    gTest&gMock learning
    机器学习 delay learning
    c++ learning
    2017 湘潭邀请赛&JSCPC G&J
    mapreduce&GFS&bigtable learning
    golang learning
    高斩仙的北京历险记
    python learning
    Codeforces Round #448 (Div. 2) B
    python之callable
  • 原文地址:https://www.cnblogs.com/GarsonZhang/p/5291931.html
Copyright © 2011-2022 走看看