C# 使DataTable LINQToDataTable中的可访问类可访问<;T>;()?
在我的代码中,我得到了需要将查询列表转换为表的实例。我使用以下方法来实现这一点:C# 使DataTable LINQToDataTable中的可访问类可访问<;T>;()?,c#,linq,.net-4.0,system.data.datatable,C#,Linq,.net 4.0,System.data.datatable,在我的代码中,我得到了需要将查询列表转换为表的实例。我使用以下方法来实现这一点: //Attach query results to DataTables public DataTable LINQToDataTable<T>(IEnumerable<T> varlist) { DataTable dtReturn = new DataTable(); // column names PropertyIn
//Attach query results to DataTables
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;
}
与其在各种.cs文件中复制该方法,不如说如果它是一个自己的实用程序类,允许我编写如下内容,它会是什么样子:
DataTable gridTable = Utility.LINQToDataTable(GetGrids); // Loads Query into Table
为了避免大量重复???将方法移动到
实用程序
调用,并使其成为静态
public class Utility
{
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
// code ....
}
}
谢谢Timothy,你也是对的:)Damith获得了投票权——纯粹是因为他完全按照我的要求离开了电话,从而使我现有的代码完全保留。
public class Utility
{
public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
// code ....
}
}
DataTable gridTable = Utility.LINQToDataTable(GetGrids);
public static class EnumerableExtensions
{
public static DataTable ToDataTable<T>(this IEnumerable<T> varlist)
{
// .. existing code here ..
}
}
GetGrids.ToDataTable();
// just like the others
GetGrids.ToList();