如何对列表中同QuestionReference的QuestionScores对象属性求和?
可以实现,以下是具体实现方式
首先修正你的QuestionScores类定义(原代码缺少class关键字):
public class QuestionScores { public string QuestionReference { get; set; } public int StudentScore { get; set; } public int QuestionScore { get; set; } }
使用LINQ的GroupBy方法就能轻松实现按QuestionReference分组并求和的需求,代码示例如下:
using System.Linq; using System.Collections.Generic; // 初始化示例数据 var scoreList = new List<QuestionScores> { new QuestionScores { QuestionReference = "U1C1", StudentScore = 1, QuestionScore = 4 }, new QuestionScores { QuestionReference = "U1C1", StudentScore = 3, QuestionScore = 4 }, new QuestionScores { QuestionReference = "U1C2", StudentScore = 2, QuestionScore = 4 } }; // 分组合并逻辑 var mergedScores = scoreList .GroupBy(s => s.QuestionReference) .Select(g => new QuestionScores { QuestionReference = g.Key, StudentScore = g.Sum(s => s.StudentScore), QuestionScore = g.Sum(s => s.QuestionScore) }) .ToList();
代码说明
GroupBy(s => s.QuestionReference):将列表按QuestionReference字段分组,相同引用的对象会被分到同一组中。Select(g => ...):遍历每个分组,创建新的QuestionScores对象,其中:g.Key就是分组对应的QuestionReference值;g.Sum(s => s.StudentScore)对组内所有对象的StudentScore求和;g.Sum(s => s.QuestionScore)对组内所有对象的QuestionScore求和。
执行上述代码后,mergedScores就是你想要的合并结果:
{ "U1C1", 4, 8 } { "U1C2", 2, 4 }
内容的提问来源于stack exchange,提问作者RWBrad
相关产品推荐
相关产品推荐

