【问题标题】:How to groupby list in c# and show result without foreach?如何在 c# 中分组列表并在没有 foreach 的情况下显示结果?
【发布时间】: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


    【解决方案1】:

    这应该可以工作(在您的 GroupBy-Expression 中):

                    Projects = c.Select(f => 
                    new GroupedProjectForShowbackSummary()
                    {
                        Id = f.ProjectId,
                        Name = f.Project.Name,
                        TotalPrice = f.Price
                    }).ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多