问题描述
我想要一个功能,它接收一个datatable&返回一个列表(对象不是DataRow)例如。 :
我知道我可以做到这一点(但这需要列名称):
// Datatable dt =从数据库查询&有3列代码,描述& ShortCode
列表< object> rtn = new List< object>();
var x =从dt.select()中的vals
选择新
{
代码= vals [代码],
描述= vals [Description],
ShortCode = vals [ShortCode],
};
rtn.AddRange(x)
return rtn;
我想要的是一个通用版本,以便我可以传入任何datatable&它将基于datatable中的列名生成。
由于在编译时不知道属性名称,而是要使用JSON序列化的数据,可以使用以下创建一个字典列表。如果使用Newtonsoft JSON,则序列化将以JSON对象格式转换关键值对。
IEnumerable<字典< string,object>> result = dt.Select()。选择(x => x.ItemArray.Select((a,i)=> new {Name = dt.Columns [i] .ColumnName,Value = a})
.ToDictionary(a => a.Name,a => a.Value));
I want a function which takes in a datatable & returns a List (object is not DataRow)Eg. :
I know I can do this (but this requires column names to be known) :
// Datatable dt = Filled from a Database query & has 3 columns Code,Description & ShortCode
List<object> rtn = new List<object>();
var x = from vals in dt.Select()
select new
{
Code = vals["Code"],
Description = vals["Description"],
ShortCode = vals["ShortCode"],
};
rtn.AddRange(x)
return rtn;
What i want is a generic version so that i can pass in any datatable & it will generate based on column names in the datatable.
Since the property names are not known at compile time and you want to use the data for JSON serialization, you can use the following to create a list of dictionary. If you use Newtonsoft JSON, then the serialization takes care of converting the key value pairs in a JSON object format.
IEnumerable<Dictionary<string,object>> result = dt.Select().Select(x => x.ItemArray.Select((a, i) => new { Name = dt.Columns[i].ColumnName, Value = a })
.ToDictionary(a => a.Name, a => a.Value));
这篇关于将DataTable转换为LINQ匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!