如何将LINQ结果转换为DATATABLE?
有没有办法在不逐步遍历每个元素的情况下将LINQ表达式的结果转换为DataTable
?
没有踩过每个元素就没有办法创造它。 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 }
相信这位博主 ,但我在这里改进了他的算法。 让自己成为一种扩展方法:
public static DataTable ToADOTable(this IEnumerable 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); }
用法:
上述就是C#学习教程:如何将LINQ结果转换为DATATABLE?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
DataTable dt = query.ToADOTable();
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1006943.html