使用Linq和Group by将数据表转换为对象 [英] Convert Datatable to Object with Linq and Group by
本文介绍了使用Linq和Group by将数据表转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试将数据表转换为特殊格式的JSON
I try to convert datatable into JSON with special format
DataTable中的数据如下
Data in DataTable is as follow
col1 col2 col3 col4
---------------------
A B c D1
A B c D2
A B c D3
尝试将其转换为类似对象的数组
Try to convert it to a object array like
class obj {
var col1;
var col2;
var col3;
list<string> col4;
}
我尝试使用linq,但是有点卡住了.
I try to use linq, but kinda get stuck.
var result = from row in dt.AsEnumerable()
group row by new
{
c1 = row["col1"],
c2 = row["col2"],
c3 = row["col3"]
}
into section
select new
{
item = section.Key
};
推荐答案
var result = from row in dt.AsEnumerable()
group row by new
{
c1 = r.Field<string>("col1"),
c2 = r.Field<string>("col2"),
c3 = r.Field<string>("col3")
} into section
select new
{
col1 = section.Key.c1,
col2 = section.Key.c2,
col3 = section.Key.c2,
col4 = section.Select(r => r.Field<string>("col4")).ToList()
};
这篇关于使用Linq和Group by将数据表转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文