首页 > Windows开发 > 详细

.NET C# 泛型集合转DataTable

时间:2019-10-25 18:23:45      阅读:149      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/jeff151013/p/11739359.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!