-1

As I'm a beginner in c# I need help !!! . I have a .csv file containing Students details in following columns, All I need here is based on the highest marks scored by the individuals , I need to get the output as follows: (/* The data's in csv file are, say may be 100 in each row and column cell */)

Name ,Maths,Science,English(header of csv)

Akash, 80, 67 , 54

Manoj, 64, 56 , 72

Subas, 78, 84 , 63

I can do the read operation and displayed the whole line. But my problem is I want to display the Name of the student and subject from the highest score from each subject.

Sample Output:

English- Manoj

Maths - Subas

Science- Akash

I'm stuck in middle and any answers without using VB are highly appreciated.

cjgeez
  • 11
  • 4

1 Answers1

0

I don't see how your requirement description matches with the sample output. Here is the code to get each subject and the student with the highest grade in which.

List<string[]> data = new List<string[]>();

using (StringReader sr = new StringReader(csvText))
{
    while (sr.Peek() > 0)
    {
        data.Add(sr.ReadLine().Split(','));
    }
}

//Iterates through columns, skipping first one (names)
List<string> output = new List<string>();
for (int i = 1; i < data[0].Count(); i++)
{
    string subjectName = data[0][i];
    Dictionary<string,int> grades = new Dictionary<string, int>();
    //Iterates through rows, skipping first one (headers)
    for (int j = 1; j < data.Count; j++)
    {
        grades.Add(data[j][0],Convert.ToInt32(data[i][j]));
    }
    output.Add(subjectName + " - " + grades.Aggregate((l, r) => l.Value > r.Value ? l : r).Key);
}

Credit to answers in this question for the Aggregate linq: Get key of highest value in Dictionary

Community
  • 1
  • 1
Thor
  • 498
  • 1
  • 6
  • 15
  • Thanks a lot Thor !!!... I'm i guess it is possible.... First i had the idea of taking the names column alone in a List , later for numerical i thought of taking the marks column in List... Finally i put on the logic part of getting the highest mark and name... Anyways thanks for the help :D – cjgeez Jul 18 '16 at 01:53
  • 1
    By all means include your solution here as well so others can pick the one that tickles their fancy. – Thor Jul 18 '16 at 07:02