在我的WebAPI中,我使用EF。我目前正在使用LINQ语句获取我的数据。
我的LINQ是:
var output = _context.CarMakes
.Select(x => new
{
id= x.CarId,
make = x.CarMake,
year = x.Year,
status = x.Status
});
my data返回为:
[
{
"id": 1,
"make": "Ford",
"year" : 2020,
"model" : "Focus"
},
{
"id" : 2,
"make" :"Ford",
"year" : 1994,
"model" : "F-150"
},
{
"id" : 3,
"make" : "Chevy",
"year" : 2022,
"model" : "Silverado"
}
]
我怎么能得到它的返回,所以它的分组,所以我可以使用它在一个TreeView导航菜单,如:我应该做什么改变。net代码?
Ford:
2020
Focus
1994
F-150
Chevy
2022
Silverado
您需要使用group by来获得所需的结果,下面是一个示例:
var result = _context.CarMakes.GroupBy(x => x.make)
.Select(g => new {
Make = g.Key,
Models = g.GroupBy(x => x.year)
.Select(y => new {
Year = y.Key,
Name = y.Select(z => z.model)
})
});
您必须在make
和year
字段上执行group by,然后选择属于这些分组的所有汽车。然后在前端,您可以使用这些返回的数据来创建一个嵌套的树视图。
var output = _context.CarMakes
.Select(x => new
{
id = x.CarId,
make = x.CarMake,
year = x.Year,
status = x.Status
})
.GroupBy(x => new { x.make, x.year })
.Select(g => new
{
make = g.Key.make,
year = g.Key.year,
cars = g.Select(x => new { id = x.id, status = x.status })
});