elena1234

AverageStudentGrades

Jan 1st, 2021 (edited)
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace AverageStudentGrades
  6. {
  7.     static class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.  
  12.             int numberOfStudents = int.Parse(Console.ReadLine());
  13.             var dictStudentGrades = new Dictionary<string, List<decimal>>();
  14.             for (int i = 0; i < numberOfStudents; i++)
  15.             {
  16.                 string[] input = Console.ReadLine().Split(" ",StringSplitOptions.RemoveEmptyEntries);
  17.                 string name = input[0];
  18.                 decimal grade = decimal.Parse(input[1]);
  19.                 if (!dictStudentGrades.ContainsKey(name))
  20.                 {
  21.                     dictStudentGrades[name] = new List<decimal>();
  22.                     dictStudentGrades[name].Add(grade);
  23.                 }
  24.  
  25.                 else
  26.                 {
  27.                     dictStudentGrades[name].Add(grade);
  28.                 }
  29.             }
  30.  
  31.             foreach (var (student, grades) in dictStudentGrades)
  32.             {
  33.                 string allGrades= string.Join(" ", grades.Select(grade=> grade.ToString("F2")));
  34.                 decimal averageGrade = grades.Count > 0 ? grades.Average() : 0; // for Average every time you must check if count > 0
  35.                 Console.WriteLine($"{student} -> {allGrades} (avg: {averageGrade:F2})");
  36.             }
  37.         }
  38.     }
  39. }
Add Comment
Please, Sign In to add comment