在 group by 子句中获取 LINQ 中的属性

Get properties in LINQ inside group by clause

我是 LINQ 的新手,我正在尝试按两列对列表进行分组并使用计数聚合函数,但我不确定如何正确编写此查询。

这是我的 class

public class Result
    { 
        public string? Type { get; set; }
        public int Age { get; set; }
        public string? Name { get; set; }
        public string? Description { get; set; }
        public int Count { get; set; }
    }

首先我从 dataTable 中读取了一些数据并将其添加到没有 Count 属性

Result 列表中
List<Result> list = new();
foreach (DataRow row in dataTable.Rows)
    {
    list.Add(new Result
                {
                    Type =row["Type"].ToString(),
                    Age = int.Parse(row["Age"].ToString()),
                    Name = row["Name"].ToString(),
                    Description = row["Description"].ToString(),
                });
    }

现在我想按 AgeType 分组,我写了这个查询,它 returns 是正确的结果,但我想知道是否有另一种更简洁的编写方式这而不是使用 Select().FirstOrDefault() ?

IEnumerable<Result> myResult = list.GroupBy(x => new { x.Age, x.Type }).Select(gr =>
             new Result
             {
                 Age = gr.Key.Age,
                 Type = gr.Key.Type,
                 Name = gr.Select(x => x.Name).FirstOrDefault(),
                 Description = gr.Select(x => x.Description).FirstOrDefault(),
                 Count = gr.Count()
             }).ToList();

你可以尝试使用FirstOrDefault()?.来简化使用Null-conditional

IEnumerable<Result> myResult = list.GroupBy(x => new { x.Age, x.Type }).Select(gr =>
     new Result
     {
         Age = gr.Key.Age,
         Type = gr.Key.Type,
         Name = gr.FirstOrDefault()?.Name,
         Description = gr.FirstOrDefault()?.Description,
         Count = gr.Count()
     }).ToList();