码迷,mamicode.com
首页 > Windows程序 > 详细

C#将LINQ数据集转换为Datatable

时间:2017-06-26 10:35:47      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:c#   linq   转换   

C#将LINQ数据集转换为Datatable


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

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

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

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

     if (varlist == nullreturn 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/

本文出自 “世界都一样” 博客,请务必保留此出处http://970076933.blog.51cto.com/9767314/1941691

C#将LINQ数据集转换为Datatable

标签:c#   linq   转换   

原文地址:http://970076933.blog.51cto.com/9767314/1941691

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!