C#将LINQ数据集转换为Datatable
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#将LINQ数据集转换为Datatable相关的知识,希望对你有一定的参考价值。
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/
本文出自 “世界都一样” 博客,请务必保留此出处http://970076933.blog.51cto.com/9767314/1941691
以上是关于C#将LINQ数据集转换为Datatable的主要内容,如果未能解决你的问题,请参考以下文章
C# 将带有 Case 语句的 SQL 查询转换为 LINQ