最佳实践:将LINQ查询结果转换为DataTable而不进行循环
将LINQ-Query结果转换为新的DataTable
的最佳做法是什么?
我能找到一个比每个结果项更好的解决方案吗?
编辑 AnonymousType
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:我有例外:
除Contains()运算符外,本地序列不能用于查询运算符的LINQ to SQL实现。
当我尝试执行查询并在此处找到解决方案IEnumerable.Except不会工作,所以我该怎么办?
并需要linq的帮助
使用Linq数据集。 从MSDN: 从查询创建DataTable(LINQ到DataSet )
// Query the SalesOrderHeader table for orders placed // after August 8, 2001. IEnumerable query = from order in orders.AsEnumerable() where order.Field("OrderDate") > new DateTime(2001, 8, 1) select order; // Create a table from the query. DataTable boundTable = query.CopyToDataTable();
如果你有匿名类型:
来自Coder博客: 使用Linq匿名类型和CopyDataTable
它解释了如何使用MSDN的如何:实现通用类型T不是DataRow的CopyToDataTable
在DataTables通用函数中转换查询结果
DataTable ddt = new DataTable(); ddt = LINQResultToDataTable(query); public DataTable LINQResultToDataTable(IEnumerable 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应用程序,Nuget包管理器控制台中使用morelinq.2.2.0包
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
- 多个参数的Lambda表达式
- 在递归方法中使用async / await的正确方法是什么?
- 将IList 转换为BindingList
- WUApiLib IUpdateInstaller2产生错误; 一些操作系统更新安装其他人扔HResult -2145124318
- 在C#.Net中使用HttpWebRequest异步上传大文件
- Directory.GetFiles保留上次访问时间
- 动作filter中的Web Api请求内容为空
- 在VS2008中的Windows x64上调试x86 .NET应用程序
- 如何获取服务器(不是网络服务器)的IP地址,而是在Xamarin.Forms中的wifi模块上创建的TCP服务器