[英]Best Practice: Convert LINQ Query result to a DataTable without looping
將 LINQ-Query 結果轉換為新的DataTable
的最佳實踐是什么?
我能找到比foreach
每個結果項更好的解決方案嗎?
編輯匿名類型
var rslt = from eisd in empsQuery
join eng in getAllEmployees()
on eisd.EMPLOYID.Trim() equals eng.EMPLOYID.Trim()
select new
{
eisd.CompanyID,
eisd.DIRECTID,
eisd.EMPLOYID,
eisd.INACTIVE,
eisd.LEVEL,
eng.EnglishName
};
編輯2:我有例外:
本地序列不能在 LINQ to SQL 的查詢運算符實現中使用,但 Contains() 運算符除外。
當我嘗試執行查詢並在此處找到解決方案時IEnumerable.Except 不起作用,那我該怎么辦?
並且需要 linq 幫助
使用 Linq 到數據集。 來自 MSDN:從查詢創建數據表(LINQ to DataSet )
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
IEnumerable<DataRow> query =
from order in orders.AsEnumerable()
where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
select order;
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();
如果您有匿名類型:
來自 Coder 博客: 使用 Linq 匿名類型和 CopyDataTable
它解釋了如何使用 MSDN 的How to:Implement CopyToDataTable Where the Generic Type T Is Not a DataRow
在DataTables泛型函數中轉換查詢結果
DataTable ddt = new DataTable();
ddt = LINQResultToDataTable(query);
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;
}
我在 asp.net web 應用程序中使用 morelinq.2.2.0 包,Nuget 包管理器控制台
PM> Install-Package morelinq
命名空間
using MoreLinq;
我的示例存儲過程 sp_Profile() 返回配置文件詳細信息
DataTable dt = context.sp_Profile().ToDataTable();
使用 System.Reflection 並迭代查詢對象中的每條記錄。
Dim dtResult As New DataTable
Dim t As Type = objRow.GetType
Dim pi As PropertyInfo() = t.GetProperties()
For Each p As PropertyInfo In pi
dtResult.Columns.Add(p.Name)
Next
Dim newRow = dtResult.NewRow()
For Each p As PropertyInfo In pi
newRow(p.Name) = p.GetValue(objRow,Nothing)
Next
dtResult.Rows.Add(newRow.ItemArray)
Return dtResult
嘗試 Datatable dt= (from rec in dr.AsEnumerable() select rec).CopyToDataTable()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.