private List<T> TableToList<T>(T obj, DataTable tt)
        {
            System.Type type = obj.GetType();
            List<T> list = new List<T>();
            for (int i = 0; i < tt.Rows.Count; i++)
            {
                T item = (T)Activator.CreateInstance(type);                object value;                foreach (DataColumn c in tt.Columns)
                {
                    value = tt.Rows[i][c];
                    if (value != System.DBNull.Value)
                    {
                        type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
                    }
                }                list.Add(item);
            }
            return list;
        } 上面的别人的代码,我只想把DATATABLE转换为LIST<string>,DATATABLE已有,请问该方法如合调用呀?DATATABLE里的字段名如何加到LIST里?感谢呀!!LIST<string> aa=?

解决方案 »

  1.   

    我主要是想把DATATABLE里的内容转到list里,然后用list排序,在绑定到gradview,这什么做的原因是DATATABLE里的列是动态生成的,不能直接排序。
      

  2.   

    public static IList<T> FillList<T>(System.Data.IDataReader reader)  
      {
      IList<T> lst= new List<T>();
      while (reader.Read())
      {
      T RowInstance = Activator.CreateInstance<T>();
      foreach (PropertyInfo Property in typeof(T).GetProperties())
      {
      foreach (BindingFieldAttribute FieldAttr in Property.GetCustomAttributes(typeof(BindingFieldAttribute), true))
      {
      try
      {
      int Ordinal = reader.GetOrdinal(FieldAttr.FieldName);
      if (reader.GetValue(Ordinal) != DBNull.Value)
      {
      Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
      }
      }
      catch
      {
      break;
      }
      }
      }
      lst.Add(RowInstance);
      }
      return lst;
      }
      

  3.   

    BindingFieldAttribute 找不到命名空间呀!!
      

  4.   

    用datatable和datalist公用一个dataset就可以绑定了
      

  5.   

    绑定数据的时候 order by 不行?
      

  6.   


    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Reflection;namespace ssss
    {
        /// <summary>
        /// Summary description for ConvertEntity1
        /// </summary>
        public static class IDataReaderExt
        {
            public static T ReaderToModel<T>(this IDataReader dr)
            {
                //  try
                //  {
                using (dr)
                {
                    T model = Activator.CreateInstance<T>();
                    if (dr.Read())
                    {
                        Type modelType = typeof(T);
                        int count = dr.FieldCount;
                        for (int i = 0; i < count; i++)
                        {
                         //   string n = dr.GetName(i);
                            if (!IsNullOrDBNull(dr[i]))
                            { 
                                PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                                if (pi != null)
                                {
                                     pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);
                                   // pi.SetValue(model, Convert.ChangeType(dr[i], pi.PropertyType), null);
                                    //  pi.SetValue(model,HackType<pi.PropertyType)(dr[i], pi.PropertyType), null);
                                }
                            }
                        }
                        return model;
                    }
                }
                return default(T);
                //   }
                //  catch (Exception ex)
                //  {
                //      return default(T);
                //   }
            }        public static IList<T> ReaderToList<T>(this IDataReader dr)
            {
                using (dr)
                {
                    List<T> list = new List<T>();
                    Type modelType = typeof(T);
                    int count = dr.FieldCount;
                    while (dr.Read())
                    {
                        T model = Activator.CreateInstance<T>();                    for (int i = 0; i < count; i++)
                        {
                            if (!IsNullOrDBNull(dr[i]))
                            {//GetPropertyName
                                PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                                if (pi != null)
                                {
                                    pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);
                                   // pi.SetValue(model, Convert.ChangeType(dr[i], pi.PropertyType), null);
                                }
                            }
                        }
                        list.Add(model);
                    }
                    return list;
                }
            }        private static object HackType<T>(object value, T conversionType) where T : Type
            {
                //  return value == null ? new T() : (T)value;            value = IsNullOrDBNull(value) ? default(T) : (T)value;            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    if (value == null)
                        return null;
                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                    conversionType = (nullableConverter.UnderlyingType as T);
                }
                return Convert.ChangeType(value, conversionType);
            }        //这个类对可空类型进行判断转换,要不然会报错   
            private static object HackType(object value, Type conversionType)
            {
             if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    if (value == null)
                        return null;                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
                    conversionType = nullableConverter.UnderlyingType;
                }
                return Convert.ChangeType(value, conversionType);
            }
            private static bool IsNullOrDBNull(object obj)
            {
                return (obj == null || (obj is DBNull)) ? true : false;
            }        //取得DB的列对应bean的属性名           private static string GetPropertyName(string column)
            {            column = column.ToLower();            string[] narr = column.Split('_');            column = "";            for (int i = 0; i < narr.Length; i++)
                {                if (narr[i].Length > 1)
                    {                    column += narr[i].Substring(0, 1).ToUpper() + narr[i].Substring(1);                }                else
                    {                    column += narr[i].Substring(0, 1).ToUpper();                }            }            return column;        }
        }
    }
      

  7.   


    这个方法的目的是把datatable转换为 对象的集合
    调用方法 先要有对象的定义也就是一条记录的 class,
    具体:TableToList<User>((new User()),dt);
      

  8.   

    8楼说到点子上了。
    看楼主提供的方法:
    T 在这里是对象类型,这个方法要求:对象的字段名与表的列名必须对应,可以通过一定的方式来匹配。每一行就是一个对象实例,每一个列(列名与字段名成功匹配)就是一个字段。private List<T> TableToList<T>(T obj, DataTable tt)
      {
      System.Type type = obj.GetType();
      List<T> list = new List<T>();
      for (int i = 0; i < tt.Rows.Count; i++)
      {
      T item = (T)Activator.CreateInstance(type);
    //实例化T类型的对象。每行对应一个对象实例。
      object value;  foreach (DataColumn c in tt.Columns)
      {
      value = tt.Rows[i][c];//每一列,对应一个字段。
      if (value != System.DBNull.Value)
      {
      type.GetProperty(c.ColumnName).SetValue(item, tt.Rows[i][c], null);
    //这个方法,要求对象的字段名与表的列名必须是相同的。所以不需要特殊处理。
      }
      }  list.Add(item);
      }
      return list;
      }
    楼主最后的意思是否只去datatable中的列么?
    LIST<string> aa=?
    这个方法就可以了。//参数:第一个为数据表,第二个是你需要的那列数据的列名 - ColumnName
    public static List<string> GetListDataByField(DataTable dtResult, string field)
            {
                List<string> vals = new List<string>();
                if (dtResult.Rows.Count > 0)
                {
                    string val = string.Empty;
                    foreach (DataRow row in dtResult.Rows)
                    {
                        val = row[field].ToString();//如果是其他类型的数据可以在这里做处理。
                        vals.Add(val);
                    }
                }            return vals;
            }
      

  9.   

    感谢各位的回复。
    //参数:第一个为数据表,第二个是你需要的那列数据的列名 - ColumnName
    public static List<string> GetListDataByField(DataTable dtResult, string field)
      {
      List<string> vals = new List<string>();
      if (dtResult.Rows.Count > 0)
      {
      string val = string.Empty;
      foreach (DataRow row in dtResult.Rows)
      {
      val = row[field].ToString();//如果是其他类型的数据可以在这里做处理。
      vals.Add(val);
      }
      }  return vals;
      }列是动态生成的,不知道列名怎么办?
      

  10.   

    public static IList<T> ReaderToList<T>(this IDataReader dr)
            {
                using (dr)
                {
                    List<T> list = new List<T>();
                    Type modelType = typeof(T);
                    int count = dr.FieldCount;
                    while (dr.Read())
                    {
                        T model = Activator.CreateInstance<T>();//错误没有为该对象定义无参数的构造函数。                    for (int i = 0; i < count; i++)
                        {
                            if (!IsNullOrDBNull(dr[i]))
                            {//GetPropertyName
                                PropertyInfo pi = modelType.GetProperty(dr.GetName(i), BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                                if (pi != null)
                                {
                                    pi.SetValue(model, HackType(dr[i], pi.PropertyType), null);
                                   // pi.SetValue(model, Convert.ChangeType(dr[i], pi.PropertyType), null);
                                }
                            }
                        }
                        list.Add(model);
                    }
                    return list;
                }
            }
    用7楼的程序,运行出错了。这是这么用的对吗?myReader有值,感谢呀!!
     IList<string> aa = IDataReaderExt.ReaderToList<string>(myReader);
      

  11.   

     (T)Activator.CreateInstance(type);
    在前面做一个转换。