如何将linq查询的结果 转换为DataTable,最简单的实现方法

public static DataTable CopyToDataTable(this IEnumerable array)
  {
  var ret = new DataTable();
  foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
  ret.Columns.Add(dp.Name, dp.PropertyType);
  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;
  }
记得添加引用空间

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Collections;

你可能感兴趣的:(.net)