C#List转DataTable


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

namespace ConsoleApp4.Extensions
{
 public static  class DBExtensions
  {

    /// <summary>
    /// List转为DataTable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    /// <returns></returns>
    public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
    {
      DataTable ret = new DataTable();
      foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
      {
        string a = dp.Name;
        ret.Columns.Add(a);
      }

      foreach (T item in array)
      {
        var Row = ret.NewRow();
        foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))


          Row[dp.Name] = dp.GetValue(item);
        ret.Rows.Add(Row);
      }
      return ret;
    }
  }
}
   //调用
      var _list = new List<Z_Result_log>();
      _list.CopyToDataTable();

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。