在我的代码中,我得到了需要将查询列表转换为表格的实例。我使用以下方法来实现这一点:
//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
以免重复多次??