List 转 DataTable 扩展方法

public static DataTable ListToDataTable<T>(this IEnumerable<T> list)
        {
            var dt = new DataTable();
            PropertyInfo[] properyInfos = typeof(T).GetProperties();
            foreach (var info in properyInfos)
            {
                //dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
                dt.Columns.Add(info.Name);
            }
            foreach (var t in list)
            {
                var row = dt.NewRow();
                foreach (var info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null);
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

你可能感兴趣的:(Datatable)