.NET C# 泛型集合转DataTable

1.功能类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace Infrastructure
{
    public static class EnumerableExtensions
    {
        public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
        {
            DataTable result = new DataTable();
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof (T)))
            {
                if (pd.PropertyType.IsGenericType && pd.PropertyType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
                    result.Columns.Add(pd.Name,Nullable.GetUnderlyingType(pd.PropertyType));
                else
                    result.Columns.Add(pd.Name, pd.PropertyType);
            }
            foreach (T item in array)
            {
                DataRow row = result.NewRow();
                foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(T)))
                    row[pd.Name] = pd.GetValue(item) ?? DBNull.Value;
                result.Rows.Add(row);
            }
            return result;
        }
    }
}
2.调用方式

List<T> items = new List<T>();

xxx //为items赋值

DataTable dataTable = EnumerableExtensions.CopyToDataTable(items);//调用方法

.NET C# 泛型集合转DataTable

上一篇:Windows server 2012 出现大量无名已断开连接用户清楚办法


下一篇:C#循环 — break VS continue