NET CORE listT 怎么按给定的字符串作为字段分组求和
要按给定的字符串字段分组并求和,您可以使用LINQ的GroupBy和Sum方法来实现。以下是一个示例代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
List<Person> people = new List<Person>()
{
new Person() { Name = "John", Category = "A", Score = 10 },
new Person() { Name = "Alice", Category = "A", Score = 20 },
new Person() { Name = "Bob", Category = "B", Score = 30 },
new Person() { Name = "Charlie", Category = "B", Score = 40 },
new Person() { Name = "David", Category = "C", Score = 50 },
};
var sumByCategory = people.GroupBy(p => p.Category)
.Select(g => new { Category = g.Key, TotalScore = g.Sum(p => p.Score) });
foreach(var result in sumByCategory)
{
Console.WriteLine($"Category: {result.Category}, Total Score: {result.TotalScore}");
}
}
}
public class Person
{
public string Name { get; set; }
public string Category { get; set; }
public int Score { get; set; }
}
在上面的示例中,我们首先定义了一个Person类,其中包含Name(姓名)、Category(类别)和Score(分数)属性。
然后,我们创建了一个包含多个Person对象的List<Person>。我们使用GroupBy方法按Category字段进行分组,并使用Sum方法计算每个组的总分数。
最后,我们使用foreach循环遍历每个分组的结果,并打印出类别和总分数。
输出将是:
Category: A, Total Score: 30
Category: B, Total Score: 70
Category: C, Total Score: 50
您可以根据自己的需求修改示例代码中的类和字段
原文地址: https://www.cveoy.top/t/topic/ibPM 著作权归作者所有。请勿转载和采集!