【发布时间】:2021-07-16 13:43:48
【问题描述】:
我正在使用 .net core 5 web api 项目。我有以下课程:
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;
我知道我首先使用它,它只返回第一个项目,但我想返回所有项目,如果我切换到 list int id for ex,它会告诉我:
[
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
}
]
}
]
附:获取所有这样的项目。
【问题讨论】:
标签: c# linq asp.net-core group-by