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

namespace SessionKeyGet.Extensions
{
    public static class DatatableExtension
    {
        public static DataTable ToDataTable<T>(this IList<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (PropertyDescriptor prop in props)
            {
                if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType));
                else
                    table.Columns.Add(prop.Name, prop.PropertyType);
            }
            foreach (T item in data)
            {
                object[] values = new object[props.Count];
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = props[i].GetValue(item);
                }
                table.Rows.Add(values);
            }
            return table;
        }
    }
}

 

相关文章:

  • 2021-10-30
  • 2021-05-17
  • 2021-11-13
  • 2021-08-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
猜你喜欢
  • 2022-12-23
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案