在我的代码中,我得到了需要将查询列表转换为表的实例。我使用以下方法来实现这一点:
//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;
}
它工作得很好,在下面的例子中:
DataTable gridTable = LINQToDataTable(GetGrids); // Loads Query into Table
而不是在各种.cs文件中复制该方法-如果它是一个自己的实用程序类,允许我编写以下内容,它会是什么样子:
DataTable gridTable = Utility.LINQToDataTable(GetGrids); // Loads Query into Table
以避免大量重复??
将方法移动到Utility
调用并使其成为static
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();