本文介绍了喂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结果到一个数据行
发布评论