• 00
  • :
  • 00
  • :
  • 00

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;

        }

 

posted @ 2016-03-18 14:24  Garson_Zhang  阅读(979)  评论(0编辑  收藏  举报