喂LINQ结果到一个数据行

编程入门 行业动态 更新时间:2024-10-12 03:21:32
本文介绍了喂LINQ结果到一个数据行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

本作品:

var Result = from e in actual.Elements select new { Key = e.Key, ValueNumber = e.Value.ValueNumber, ValueString = e.Value.ValueString, ValueBinary = e.Value.ValueBinary, ValueDateTime = e.Value.ValueDateTime };

但是,这并不工作:​​

But this doesn't work:

IEnumerable<DataRow> Result = from e in actual.Elements select new DataRow { Key = e.Key, ValueNumber = e.Value.ValueNumber, ValueString = e.Value.ValueString, ValueBinary = e.Value.ValueBinary, ValueDateTime = e.Value.ValueDateTime }; DataTable dt = Result.CopyToDataTable(Result);

你能不能帮我?我想代码的第二位的工作,这样我可以把它放到数据表。我认识的语法是#2完全错误的。你如何使用LINQ像这样指定列?

Can you fix it for me? I want the second bit of code to work so that I can put it into the DataTable. I realize the syntax is totally wrong in #2. How do you specify a column using LINQ like this?

推荐答案

您可以编写采取任何的IEnumerable< T> ,使用反射来获取的PropertyDescriptor 取值和T有关,并创建一个的DataColumn 每个

You can write a simple extension method that takes any IEnumerable<T>, uses reflection to get the PropertyDescriptors associated with T, and creates a DataColumn for each

public static DataTable PropertiesToDataTable(this IEnumerable<T> source) { DataTable dt = new DataTable(); var props = TypeDescriptor.GetProperties(typeof(T)); foreach (PropertyDescriptor prop in props) { DataColumn dc = dt.Columns.Add(prop.Name,prop.PropertyType); dc.Caption = prop.DisplayName; dc.ReadOnly = prop.IsReadOnly; } foreach (T item in source) { DataRow dr = dt.Rows.NewRow(); foreach (PropertyDescriptor prop in props) dr[prop.Name] = prop.GetValue(item); dt.Rows.Add(dr); } return dt; }

更多推荐

喂LINQ结果到一个数据行

本文发布于:2023-06-11 03:32:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/625752.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!