You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对列表中同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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:52:42