c# - 使用 Linq 将项目添加到列表

标签 c# linq

我让我的类(class)尽可能简单。以下是我的类(class)。

public class QuestionData
{
    property QuestionID int {get; set;}
    property Question String {get; set;}
    property QuestionScore int {get; set;}
    <!---Few More Properties ----!>
}
public class QuestionInfo
{
    property QuestionID int {get; set;}
    property Question String {get; set;}
    property QuestionFinalScore int {get; set;}
    property List<QuestionData> ListAchieved {get; set;}
}

下面是我的示例数据

Question | QuestionID | QuestionScore 
    Q1   |      1     |     10
    Q1   |      1     |     20
    Q2   |      2     |     10
    Q2   |      2     |     -5

经过 Linq 中的群组后以及以下 Query

List<QuestionData> FinalSet = // Filled with Data Here
IEnumerable<QuestionInfo> datapoints = from f in FinalSet
    group f by new { f.QuestionID, f.Question } into fGroup
    select new QuestionInfo()
    {
        QuestionID = fGroup.Key.QuestionID
        , Question = fGroup.Key.Question,
        , QuestionFinalScore = fGroup.Sum(g => g.QuestionScore)
        //, ListAchieved = This is where IDK what to do :(
    };

下面是我的输出

Question | QuestionID | QuestionScore 
    Q1   |      1     |     30
    Q2   |      2     |     5

现在,如果您看到我的类(class) QuestionInfo ,我需要添加全部QuestionData我的问题ListAchieved属性,以便我可以在列表中显示 Question QuestionFinalScore结果就是这样。

任何人都可以指出我需要做什么才能将所有这些项目添加到我的 List<QuestionData> 中属性按 QuestionID 分组和Question

最佳答案

我想你想这样做:

, ListAchieved = fGroup.ToList()

这会将一组的所有项目放入一个列表中。

关于c# - 使用 Linq 将项目添加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882827/

相关文章:

c# - 将对象名称与数字组合

c# - 通过 Linq 对字符串进行排序

c# - 服务上的 AccessViolationException

c# - 如何使用 LinQ 从数据集中选择多列到字符串列表中

linq - Entity Framework 、代码优先和全文搜索

c# - ServiceStack 和非数据库对象

c# - 哪个 Eyeshot 实体效率更高?

c# - 如何过滤枚举并在下拉列表中使用它

c# - 使用 XElement 时如何输入文本

c# - 在 NHibernate 上使用 Linq 的 IN 运算符