我使用的是.net核心5网络应用程序接口项目。我有以下课程:
public class GroupedShowbackSummaryListDto
{
public int RuleId { get; set; }
public string RuleName { get; set; }
public decimal TotalPrice { get; set; }
public List<GroupedProjectForShowbackSummary> Projects { get; set; }
}
public class GroupedProjectForShowbackSummary
{
public int? Id { get; set; }
public string Name { get; set; }
public decimal TotalPrice { get; set; }
}我想按规则id分组并显示项目列表作为响应,我正在尝试:
var queryable = _context.ShowbackSummaries.Where(x => x.ProjectId != null).AsQueryable();
var summary = queryable.ToList();
var grouped = summary.GroupBy(x => x.ShowbackRuleId).Select(c => new GroupedShowbackSummaryListDto
{
RuleId = c.Key,
RuleName = c.Select(f => f.ShowbackRule.Name).First(),
TotalPrice = c.Select(f => f.Price).Sum(),
Projects = new List<GroupedProjectForShowbackSummary>
{
new()
{
Id = c.Select(f => f.ProjectId).First(),
Name = c.Select(f => f.Project.Name).First(),
TotalPrice = c.Select(f => f.Price).First()
}
}
}).ToList();
return grouped;我知道我使用的是first,它只返回first project,但我想返回all,如果我切换到为ex列出int id,它将显示:
[
100,
101,
...
]我希望我当前的回复有多个结果:
[
{
"ruleId": 1,
"ruleName": "rule-1",
"totalPrice": 400,
"projects": [
{
"id": 1169,
"name": "lubos-cncf",
"totalPrice": 200
}
]
},
{
"ruleId": 2,
"ruleName": "rule-2",
"totalPrice": 300,
"projects": [
{
"id": 1169,
"name": "lubos-cncf",
"totalPrice": 300
}
]
}
]附言:得到所有像这样的项目。
发布于 2021-07-16 21:48:00
这应该可以工作(在GroupBy-Expression中):
Projects = c.Select(f =>
new GroupedProjectForShowbackSummary()
{
Id = f.ProjectId,
Name = f.Project.Name,
TotalPrice = f.Price
}).ToList()https://stackoverflow.com/questions/68410088
复制相似问题