c# DataTable转List 和 List转 DataTable

 
 
1、///将List<>转换为DataTable 
public static DataTable ListToDataTable<T>(IEnumerable<T> collection)
       {

           var props = typeof(T).GetProperties();

           var dt = new DataTable();

           dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());

           if (collection.Count() > 0)
           {

               for (int i = 0; i < collection.Count(); i++)
               {

                   ArrayList tempList = new ArrayList();

                   foreach (PropertyInfo pi in props)
                   {

                       object obj = pi.GetValue(collection.ElementAt(i), null);

                       tempList.Add(obj);

                   }

                   object[] array = tempList.ToArray();

                   dt.LoadDataRow(array, true);

               }

           }

           return dt;

       }
2、将DataTable转换为List<>
  调用方法:  List<MaterialInfo>pcadTableInfos = ModelConvertHelper<MaterialInfo>.ConvertToModel(dt);

   public static class ModelConvertHelper<T> where T : new()
       {
           public static List<T> ConvertToModel(DataTable dt)
           {
               // 定义的集合    
               List<T> ts = new List<T>();


               // 获得此模型的类型   
               Type type = typeof(T);
               string tempName = "";


               foreach (DataRow dr in dt.Rows)
               {
                   T t = new T();
                   // 获得此模型的公共属性      
                   PropertyInfo[] propertys = t.GetType().GetProperties();
                   foreach (PropertyInfo pi in propertys)
                   {
                       tempName = pi.Name;  // 检查DataTable是否包含此列    


                       if (dt.Columns.Contains(tempName))
                       {
                           // 判断此属性是否有Setter      
                           if (!pi.CanWrite) continue;


                           object value = dr[tempName];
                           if (value != DBNull.Value)
                               pi.SetValue(t, value, null);
                       }
                   }
                   ts.Add(t);
               }
               return ts;
           }
       }    


猜你喜欢

转载自blog.csdn.net/wxstar8/article/details/68928768