如何在c#中将var类型转换为datatable? [英] how to convert var type to datatable in c#?
本文介绍了如何在c#中将var类型转换为datatable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var recordsV2 = NgDb.UCB_Cimplicity_EReferral_GetFulfillmentsV2(companyID,clientID,programID,supplierName).ToList();
如何将上述var recordsV2转换为datatable。
提前谢谢。
解决方案
IEnumerable< datarow> query = NgDb.UCB_Cimplicity_EReferral_GetFulfillmentsV2(companyID,clientID,programID,supplierName);
// 从查询中创建一个表。
DataTable boundTable = query。 CopyToDataTable< datarow>();
或者可以使用反射的自定义方法将LINQ结果转换为数据表
public DataTable LINQResultToDataTable< t>(IEnumerable< t> Linqlist)
{
DataTable dt = new DataTable();
PropertyInfo [] columns = null ;
if (Linqlist == null ) return dt;
foreach (T记录 in Linqlist)
{
if (columns == null )
{
columns =((Type)Record。的GetType())的GetProperties();
foreach (PropertyInfo GetProperty 列)
{
类型colType = GetProperty.PropertyType;
if ((colType.IsGenericType)&&(colType.GetGenericTypeDefinition()
== typeof (Nullable<>)))
{
colType = colType.GetGenericArguments()[ 0 ];
}
dt.Columns.Add( new DataColumn(GetProperty.Name,colType));
}
}
DataRow dr = dt.NewRow();
foreach (PropertyInfo pinfo in columns)
{
dr [ pinfo.Name] = pinfo.GetValue(记录, null )== null ? DBNull.Value:pinfo.GetValue(Record, null );
}
dt.Rows.Add(dr);
}
return dt;
}
您好,
查看此链接:将LINQ查询结果转换为数据表
谢谢
var recordsV2 = NgDb.UCB_Cimplicity_EReferral_GetFulfillmentsV2(companyID, clientID, programID, supplierName).ToList();
how to convert the above var recordsV2 to datatable.
thanks in advance.
解决方案
IEnumerable<datarow> query = NgDb.UCB_Cimplicity_EReferral_GetFulfillmentsV2(companyID, clientID, programID, supplierName); // Create a table from the query. DataTable boundTable = query.CopyToDataTable<datarow>();
Or can use a customized method using reflection to convert LINQ result to datatable
public DataTable LINQResultToDataTable<t>(IEnumerable<t> Linqlist) { DataTable dt = new DataTable(); PropertyInfo[] columns = null; if (Linqlist == null) return dt; foreach (T Record in Linqlist) { if (columns == null) { columns = ((Type)Record.GetType()).GetProperties(); foreach (PropertyInfo GetProperty in columns) { Type colType = GetProperty.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(new DataColumn(GetProperty.Name, colType)); } } DataRow dr = dt.NewRow(); foreach (PropertyInfo pinfo in columns) { dr[pinfo.Name] = pinfo.GetValue(Record, null) == null ? DBNull.Value : pinfo.GetValue(Record, null); } dt.Rows.Add(dr); } return dt; }
Hello ,
Check this link : Convert LINQ Query Result to Datatable
Thanks
这篇关于如何在c#中将var类型转换为datatable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文