[英]How to Convert a LINQ result to DATATABLE?
有沒有辦法在不逐步遍歷每個元素的情況下將LINQ表達式的結果轉換為DataTable
?
相信這位博客 ,但我在這里改進了他的算法。 讓自己成為一種擴展方法:
public static DataTable ToADOTable<T>(this IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// Use reflection to get property names, to create table
// column names
PropertyInfo[] oProps = typeof(T).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));
}
foreach (T rec in varlist)
{
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 dt = query.ToADOTable();
沒有踩過每個元素,沒有辦法創建它。 Linq表達式在需要時進行評估,因此它將遍歷每一行(用於匹配和選擇)。
我認為您應該嘗試使用DataTable.Select()
( MSDN鏈接 )方法,因為它返回可以添加到新表的DataRow
對象數組,如下所示:
var rows = [ORIGINAL DATA TABLE].Select("id>5");
var dtb=[ORIGINAL DATA TABLE].Clone();
foreach(DataRow r in rows)
{
var newRow = dtb.NewRow();
newRow.ItemArray = r.ItemArray;
dtb.Rows.Add(newRow);//I'm doubtful if you need to call this or not
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.