.net对象转Datable

      public static DataTable GetDataTable<T>( IEnumerable<T> list,string tableName)
        {
            DataTable dtResult = new DataTable();
            dtResult.TableName = tableName;
            List<PropertyInfo> propertiyInfos = new List<PropertyInfo>();
            //生成各列
            Array.ForEach<PropertyInfo>(typeof(T).GetProperties(), p =>
            {
                propertiyInfos.Add(p);
                dtResult.Columns.Add(p.Name, p.PropertyType);
            });
            //生成各行
            foreach (var item in list)
            {
                if (item == null)
                {
                    continue;
                }
                DataRow dataRow = dtResult.NewRow();
                propertiyInfos.ForEach(p => dataRow[p.Name] = p.GetValue(item, null));
                dtResult.Rows.Add(dataRow);
            }
            return dtResult;
        }

 

posted on 2016-01-13 10:58  走过路过ボ不要错过  阅读(273)  评论(0编辑  收藏  举报

导航