ListToDataTable

public static DataTable ToDataTable<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;
       }

posted on 2016-12-24 21:56  焦会锋  阅读(310)  评论(0编辑  收藏  举报

导航