-1

I am trying to do aggregate functions in a list of generics in C# based on an id

class Student{
  public int id { get; set; }
  public int marks { get; set; }
}

class Main {
  List<Student> StudentList = new List<Student>();
  List.Add(new Student(1,55);
  List.Add(new student(2,65);
  List.Add(new student(4,75);
  List.Add(new student(1,65);
  List.Add(new student(2,45);

  foreach(var st in StudentList) {
    Console.WriteLine(st.id + " " + st.marks);
  }
}

But this returns

1 55
2 65
4 75
1 65
2 45

I want to return the following result:

1 120
2 110
4 75
Farshid Zaker
  • 1,960
  • 2
  • 22
  • 39
Learn AspNet
  • 1,192
  • 3
  • 34
  • 74
  • 1
    Take a look at https://stackoverflow.com/questions/16100900/select-multiple-fields-group-by-and-sum – Farshid Zaker Mar 09 '19 at 23:17
  • Please take more care when posting code, this one is littered with errors. – DavidG Mar 09 '19 at 23:18
  • Possible duplicate of [Select multiple fields group by and sum](https://stackoverflow.com/questions/16100900/select-multiple-fields-group-by-and-sum) – Richard II Mar 10 '19 at 00:11

2 Answers2

2

This can be done with the Linq GroupBy function:

var totals = StudentList
    .GroupBy(sl => sl.id) //Group by ID
    .Select(g => new Student(g.Key, g.Sum(s => s.marks)));

foreach (var st in totals)
{
    Console.WriteLine(st.id + " " + st.marks);
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

You can also group with a Dictionary<int, int>.

With LINQ:

var Totals = StudentList
    .GroupBy(x => x.Id)
    .ToDictionary(x => x.Key, x => x.Select(i => i.Mark).Sum());

Without LINQ:

var Totals = new Dictionary<int, int>();

foreach (var student in StudentList)
{
    var id = student.Id;
    if (!Totals.ContainsKey(id))
    {
        Totals[id] = 0;
    }

    Totals[id] += student.Mark;
}

Then you can simply print out the results like this:

foreach (var result in Totals)
{
    Console.WriteLine($"{result.Key} {result.Value}");
}

Which Outputs:

1 120
2 110
4 75
RoadRunner
  • 25,803
  • 6
  • 42
  • 75