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