我正在尝试使用LINQ:
创建/填充对象MyObject
public class MyObject
{
public string Title { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public string Title { get; set; }
public string Color { get; set; }
public int Value { get; set; }
}
我有一个DataTable
,内容如下:
Title Color Value
----- ----- -----
Something Green 14
Title 2 Red 7
Title 4 Green 5
More Green 12
Title 8 Red 6
我将如何进行并按颜色分组创建MyObject
?我尝试使用LINQ,我对分组很好,但我不知道如何填充Items
:
var groupedObjects = from row in dataTable.AsEnumerable()
group row by row.Field<string>("Color")
into grp
select new MyObject
{
Name = grp.Key
//,Items = this is where I don't know how to continue.
//Subselect to get all items where grp.Key == row.Field<string>("Color")?
};
我的最终结果应该是这样的(JSON,我想这会是List<MyObject>
):
{
"Title" : "Green",
"Items": [
{
"Title" : "Something",
"Color" : "Green",
"Value" : 14
},
{
"Title" : "Title 4",
"Color" : "Green",
"Value" : 5
}
],
"Title" : "Red",
"Items": [
{
"Title" : "Title 2",
"Color" : "Red",
"Value" : 7
},
{
"Title" : "Title 8",
"Color" : "Red",
"Value" : 6
}
]
}
答案 0 :(得分:1)
您已经拥有这些群组,因此您只需要在群组中投放项目并将其转换为项目,您就不需要额外的过滤:
var groupedObjects = from row in dataTable.AsEnumerable()
group row by row.Field<string>("Color")
into grp
select new MyObject
{
Name = grp.Key,
Items = grp.Select(x => new Item
{
Title = x.Field<string>("Title"),
Color = x.Field<string>("Color"),
Value = x.Field<int>("Value")
}).ToList()
};