我是 LINQ 新手,我正在嘗試將串列按兩列分組并使用 count 聚合函式,但我不確定如何正確撰寫此查詢。
這是我的課
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; }
}
首先,我從 a 讀取一些資料dataTable并將其添加到Result沒有Count屬性的串列中
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(),
});
}
現在我想按Ageand分組Type,我寫了這個查詢,它回傳了正確的結果,但我想知道是否有另一種更簡潔的方法來寫這個而不是使用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();
uj5u.com熱心網友回復:
您可以嘗試使用Null-conditionalFirstOrDefault()?.使其變得簡單
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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/458835.html
