-1

I need to read the best grades from the Grades.txt file and save the best grades of individual students in the BestGrades.txt file. Unfortunately I can only view student data on the console. Could someone help me?

using System;
using System.IO;

namespace Projekt
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
            string line;
            System.IO.StreamReader file =
        new System.IO.StreamReader(@"C:\Users\eryks\Desktop\Grades.txt");

            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);
                counter++;
            }

            file.Close();
        }
    }
}

Console, and Grade.txt

Grades.txt:

1,Jan,Kowalski,Informatyka,5
2,Wiktoria,Prietz,Informatyka,6
3,Jakub,Mateja,Informatyka,3
id,name,lastname,school subject,grade
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
WooFix
  • 11
  • 2

1 Answers1

1

Hence your question is asking for ordering grades with out mentioning a model, and I assume your grade is the last value in each line of the CSV file. So I have chosen a simple solution is using SortedList with key and value, so the grades become integer and the your line is string type.

I have build the solution your existing code, with some inline explanation.

Here is the code:

SortedList<int, string> sortedList = new SortedList<int, string>();

while ((line = file.ReadLine()) != null)
{
    System.Console.WriteLine(line);
    // this is to prevent parsing the header
    if (!line.StartsWith("id"))
    {
        // Extract the grade from the line
        var s = line.Substring(1 + line.LastIndexOf(",", StringComparison.Ordinal));
        // Parse the grade to integer
        var grade = int.Parse(s);
        // Adding the grade and line to our sorted list
        sortedList.Add(grade, line);
    }

    counter++;
}

So lets test it

foreach (var keyValuePair in sortedList)
{
    var data = keyValuePair.Key;
    var grade = keyValuePair.Value;
    Console.WriteLine($"{data} {grade}");
}

So with your input, I get this organic ordered output with low grade to high order:

3 3,Jakub,Mateja,Informatyka,3
5 1,Jan,Kowalski,Informatyka,5
6 2,Wiktoria,Prietz,Informatyka,6

I guess if you need with high grade to low order, just added OrderBy to the list:

sortedList.OrderBy(e => e.Value)

That said I suggest you create a Model object of your data and inserted to a list of object and order it. It is much better.

What I did is a conceptual solution, it has place for improvement. That part is left to you. Enjoy.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137