如何 return 一组分组项目?

How to return an array of grouped items?

我有一个简单的 GET 请求处理 return 我的所有元素。但我似乎无法弄清楚如何return分组数组中的那些元素,按名称和日期分组

我的模型:

public class Event
{
   [Key]
   public long ID { get; set; }

   [Required]
   public DateTime date { get; set; }

   [Required]
   public string name { get; set; }
}

这是我对 return 所有元素的 GET 请求

[Route("api/events")]
[HttpGet]
public async Task<ActionResult<IEnumerable<Event>>> GetEvents()
{
   return await _context.Events.ToListAsync();
}

您可以这样定义 DTO:

public class GroupedEventsDto
{
    public DateTime Date { get; set; }
    public string Name { get; set; }

    // although you already know date and name, 
    // so you could have the list of IDs only
    public List<Event> Events { get; set; }
}

并像这样简单地做:

[HttpGet("api/events")]
public async Task<ActionResult<IEnumerable<GroupedEventsDto>>> GetEvents()
{
    var events = await context.Events.ToArrayAsync();

    var data = events 
       .GroupBy(x => new { x.date, x.name })
       .Select(grp => new GroupedEventsDto
       {
          Date = grp.Key.date,
          Name = grp.Key.name,
          Events = grp.ToList()
        })
        .ToList();

    return data;
}

这会产生一个 JSON 喜欢

[
    {
        "Name": "a",
        "Date": "2020-08-22",
        "Events": [
            {
                "Name": "a",
                "Date": "2020-08-22",
                "Id": 1
            }, ...
        ]
    },
    {
        "Name": "b",
        "Date": "2020-08-22",
        "Events": [
            {
                "Name": "b",
                "Date": "2020-08-22",
                "Id": 2
            }, ...
        ]
    },
    ...
]

当然,您最终需要的属性会在 GroupedEventsDto

中发生变化