我如何获得代数、几何和计算机科学的成绩?

问题描述 投票:0回答:1

这里我们有Main方法

static void Main(string[] args)
{
    var group = new List<SchoolBoy>();
    group.Add(new SchoolBoy
    {
        Class = 8,
        Surname = "Smith",
        Initials = "TK",
        Mark = 5,
        Object = "Algebra"
    });
    group.Add(new SchoolBoy
    {
        Class = 8,
        Surname = "Smith",
        Initials = "TK",
        Mark = 4,
        Object = "Informatics"
    });
    group.Add(new SchoolBoy
    {
        Class = 8,
        Surname = "Smith",
        Initials = "TK",
        Mark = 3,
        Object = "Geometry"
    });

    var result = group.GroupBy(g => new { g.Class, g.Surname, g.Initials})
        .Select(s => new
        {
            s.Key.Class,
            s.Key.Surname,
            s.Key.Initials,
            Algebra = ???,
            Geometry = ???,
            Informatics = ???
        }).OrderBy(o => o.Class);

    foreach (var item in result)
    {
        Console.WriteLine($"Class: {item.Class} | Surname: {item.Surname} | Initials: {item.Initials} | Algebra:{item.Algebra}" +
            $"| Geometry: {item.Geometry} | Informatics: {item.Informatics}");
    }
}

代数 = s.Count(s => s.Object == "代数"), 但这里很明显会输出1。 我想要代数 5 几何 3 计算机科学 4 这是给八年级学生的

c# linq
1个回答
0
投票

如果我理解你的权利,每个学生都可以为给定的Object获得

几个分数
(例如“Smith”可以用
5, 4, 3, 5, 5
来表示“代数”)。如果是你的情况,我们必须 将这些
Mark
聚合起来,说成一个字符串:

var result = group
  .GroupBy(item => (item.Class, item.Surname, item.Initials),
           item => (item.Object, item.Mark))
  .Select(student => (
     Class       : student.Key.Class, 
     Surname     : student.Key.Surname,
     Initials    : student.Key.Initials,

     Algebra     : string.Join(", ", student
       .Where(item => item.Object == "Algebra")
       .Select(item => item.Mark)),

     Geometry    : string.Join(", ", student
       .Where(item => item.Object == "Geometry")
       .Select(item => item.Mark)),

     Informatics : string.Join(", ", student
       .Where(item => item.Object == "Informatics")
       .Select(item => item.Mark))
   ))
© www.soinside.com 2019 - 2024. All rights reserved.