gpt4 book ai didi

c# - 用于筛选和循环遍历多个表的 ASP.NET LINQ 查询

转载 作者:行者123 更新时间:2023-11-30 19:53:40 24 4
gpt4 key购买 nike

我有两个独立的域模型类“App”和“AgeGroup”。 App 类包含一些基本的整数和字符串属性,AgeGroup 类也是如此。

我想要实现的是 AppOrder 的所有应用程序及其属性的 JSON 输出,这些应用程序嵌套在按其 GroupOrder 属性排序的关联 AgeGroup 中

必需的示例 JSON 输出结构

"Looped List of Age Groups, order by GroupOrder"
"Looped List of Apps, order by App Order"

First Age Group
Foo App Name
Foo App Icon
Foo App Store URL
Bar App Name
Bar App Icon
Bar App Store URL
Second Age Group
Tur App Name
Tur App Icon
Tur App Store URL
Puk App Name
Puk App Icon
Puk App Store URL
and so on...

到目前为止我的方法:

这是我的“App.cs”

public int Id { get; set; }
public string Name { get; set; }
public string StoreURL { get; set; }
public int AppOrder { get; set; }
public string AppIcon { get; set; }

public AgeGroup AgeGroup { get; set; } // Linked to AgeGroup Class
public int AgeGroupId { get; set; }

"AgeGroup.cs" 类中,我有以下内容

public int Id { get; set; }
public int GroupOrder { get; set; }
public string Name { get; set; }

并且在 AppsController.cs

    [HttpGet]
[Route("api/groups")]

public IHttpActionResult AppsByGroup ()
{
var apps = _context.Apps
.OrderBy(a => a.AppOrder)
.Select(a => new
{
a.Name,
a.StoreURL,
a.AppIcon,
AgeGroup = a.AgeGroup.Name
}).GroupBy(a => a.AgeGroup);

return Json(apps);
}

它为我提供了正确的输出,但没有年龄组名称。

[
[ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group A)
{
"Name": "First App for Group A",
"StoreURL": "some string",
"AppIcon": "icon string",
"AgeGroup": "Group A"
},
{
"Name": "2nd App Group A",
"StoreURL": "aslfdj",
"AppIcon": "asljf",
"AgeGroup": "Group A"
},
{
"Name": "3rd App Group A",
"StoreURL": "aslfdj",
"AppIcon": "alsfdj",
"AgeGroup": "Group A"
}
],
[ // Here I wanted the AgeGroup Name from the AgeGroup Table (Group B)
{
"Name": "1st App GroupB",
"StoreURL": "alsfdj",
"AppIcon": "alsdjf",
"AgeGroup": "Group B"
},

//and so on...

最佳答案

试试这个

public IHttpActionResult AppsByGroup() {

var apps = _context.Apps.OrderBy(a => a.AppOrder);
var groups = _context.AgeGroups.OrderBy(g => g.GroupOrder);

var result = groups.Select(x => new {
AgeGroupName = x.Name,
Apps = apps
.Where(y => x.Id == y.AgeGroupId)
.Select(y => new {
AppName = y.Name,
AppIcon = y.AppIcon,
StoreURL = y.StoreURL
})
});

return Json(result);
}

它给出以下输出

[
{
"AgeGroupName": "Group C",
"Apps": [
{
"AppName": "C Group App",
"AppIcon": "Some string",
"StoreURL": "64"
}
]
},
{
"AgeGroupName": "Group A",
"Apps": [
{
"AppName": "App 2nd for Group AA",
"AppIcon": "Some string",
"StoreURL": "654"
},
{
"AppName": "App 1 for Group A",
"AppIcon": "Some string",
"StoreURL": "654"
}
]
},
{
"AgeGroupName": "Group B",
"Apps": [
{
"AppName": "App 1 for Group B",
"AppIcon": "Some string",
"StoreURL": "31"
}
]
}
]

希望对您有所帮助。

关于c# - 用于筛选和循环遍历多个表的 ASP.NET LINQ 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47108961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com