In my WebAPI, I'm using EF. I'm currently getting my data out using a LINQ statement.
My LINQ is:
var output = _context.CarMakes
.Select(x => new
{
id= x.CarId,
make = x.CarMake,
year = x.Year,
status = x.Status
});
my data is returned as:
[
{
"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"
}
]
How can I get it returned so it's grouped so I can use it in a TreeView navigation menu such as: What changes should I make to the .NET code?
Ford:
2020
Focus
1994
F-150
Chevy
2022
Silverado
asked Jan 17, 2023 at 13:54
JustWantsToCode
1031 silver badge10 bronze badges
2 Answers 2
you need to use group by to get the result needed, here is an example :
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)
})
});
Sign up to request clarification or add additional context in comments.
1 Comment
JustWantsToCode
This is what I'm looking for, thanks, I need to add the ID field to this as well so when the user clicks on the mdoel, It'll take them to the details for that model, Is there a way to add the ID field for the model and still have it grouped as such?
You have to perform group by on make and year fields and then select all the cars that come under those grouping. Then in the front end, you can use this returned data to make a nested tree view.
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 })
});
answered Jan 17, 2023 at 14:19
ShubhamWagh
6653 silver badges10 bronze badges
Comments
lang-cs
makeis twice in your JSON.