C#将LINQ数据集转换为Datatable

1.方法一:(测试可用)

//通过一个公共类将LINQ数据集转换为datatable

public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)

{
     DataTable dtReturn = new DataTable();
     // column names 
     PropertyInfo[] oProps = null;

if (varlist == null) return dtReturn;

foreach (T rec in varlist)
     {
          // Use reflection to get property names, to create table, Only first time, others 
          will follow 
          if (oProps == null)
          {
               oProps = ((Type)rec.GetType()).GetProperties();
               foreach (PropertyInfo pi in oProps)
               {
                    Type colType = pi.PropertyType;

if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()      
                    ==typeof(Nullable<>)))
                     {
                         colType = colType.GetGenericArguments()[0];
                     }

dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
               }
          }

DataRow dr = dtReturn.NewRow();

foreach (PropertyInfo pi in oProps)
          {
               dr[pi.Name] = pi.GetValue(rec, null) == null ?DBNull.Value :pi.GetValue
               (rec,null);
          }

dtReturn.Rows.Add(dr);
     }
     return dtReturn;
}

调用:

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(vrCountry);

2.方法二:(未测试)

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
{
     if (query == null)
     {
          throw new ArgumentNullException("query");
     }
     
     IDbCommand cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

try
     {
          cmd.Connection.Open();
          adapter.FillSchema(dt, SchemaType.Source); 
          adapter.Fill(dt);
     }
     finally
     {
          cmd.Connection.Close();
     }
     return dt;
}

调用:

var vrCountry = from country in objEmpDataContext.CountryMaster
                        select new {country.CountryID,country.CountryName};

DataTable dt = LINQToDataTable(objEmpDataContext,vrCountry);

原文地址:http://www.c-sharpcorner.com/uploadfile/VIMAL.LAKHERA/convert-a-linq-query-resultset-to-a-datatable/

时间: 2024-10-10 22:22:35

C#将LINQ数据集转换为Datatable的相关文章

将DataTable转换为List,将List转换为DataTable的实现类

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Xmh.DBUnit { /// <summary> /// 将DataTable转换为List,将

实体类转换为DataTable

下面为实体类转换为DataTable的一个小例子: 用到了反射知识. using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Net_ConsoleApplication { class Program { stat

List&lt;T&gt;转换为DataTable

public static class DataTableExtensions    {        /// <summary>        /// 转化一个DataTable        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="list"></param>    

泛型集合转换为DataTable

在做项目中,遇到了将集合转换为DataTable的使用,在网上看了资料,在这里记录下来,分享. using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Wolfy.List2DataTable { class Pro

c#常用的Datable转换为json,以及json转换为DataTable操作方法

#region  DataTable 转换为Json字符串实例方法/// <summary>/// GetClassTypeJosn 的摘要说明/// </summary>public class GetClassTypeJosn : IHttpHandler{    /// <summary>    /// 文件名:DataTable 和Json 字符串互转    /// 版权所有:Copyright (C) Create Family Wealth liangjw 

【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable

OleDbDataAdapter方式: /// <summary> /// 读取excel的表格放到DataTable中 ---OleDbDataAdapter /// </summary> /// <param name="strSql"></param>        /// <param name="excelpath">excel路径</param> /// <returns>

数据集转换为Json

第一步:新建一个类对象  通常我会写三个属性:状态.返回信息.数据集 第二步:新建一个JSON转换类 第三步:把类对象当做参数传入JSON转换类 —————————————————————————————————————————————————————————————————————————————— /// <summary>        /// 数据集转换为json        /// </summary>        /// <param name="o

c#将list集合转换为datatable的简单办法

public static class ExtensionMethods        {        /// <summary>        /// 将List转换成DataTable        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="data"></param>

Json 字符串 转换为 DataTable数据集合

/// <summary> /// 将json转换为DataTable /// </summary> /// <param name="strJson">得到的json</param> /// <returns></returns> private DataTable JsonToDataTable(string strJson) { //转换json格式 strJson = strJson.Replace(&qu