0

The contents of the arrays (student names and test scores) are pulled from a text file in this format:

Helen Mills
25
Jake Stein
35
etc.

I have used the following code to find the highest int in marks[] and assign it to topMark, however haven't been able to figure out how to store the corresponding name as strings for topFirstname and topSurname. So in this example I would like for int topMark = 35, string topFirstname = Jake and string topSurname = Stein

int topMark = marks[0];
foreach (int value in marks)
{
    if (value > topMark) topMark = value;
}
Sunny Patel
  • 7,830
  • 2
  • 31
  • 46
  • What data structure are you using for `marks`? Are you using [LINQ](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/)? – Sunny Patel Jan 09 '20 at 21:59
  • yes i am using LINQ – DustiestHamwich Jan 09 '20 at 22:01
  • See the techniques mentioned in the answers to this question; it is not exactly the same as yours but you can figure out how to solve your problem by adapting one of these techniques. https://stackoverflow.com/questions/59634429/store-name-number-and-sort-in-size-order-based-on-the-numbers/59635180#59635180 – Eric Lippert Jan 09 '20 at 22:27

1 Answers1

1
public class Person
{
  public string Name {get;set;}
  public int Mark {get;set;}
}

public IEnumerable<Person> ParseFile(string filePath)
{
  System.IO.StreamReader file = new System.IO.StreamReader(filePath);
  while((var name = file.ReadLine()) != null)
  {
    var p = new Person();
    p.Name = name;
    p.Mark = int.TryParse(file.ReadLine());
    yield return p;
  }
  file.Close();
}

Then your main logic would just be:

var topPerson = ParseFile(@"C:...").OrderByDescending(p=>p.Mark).First();
Console.WriteLine($"Top mark: {topPerson.Mark}");
Console.WriteLine($"Top name: {topPerson.Name}");

Feel free to break the name up into first/last name if you need.

Robert McKee
  • 21,305
  • 1
  • 43
  • 57
  • Thanks i will try this. – DustiestHamwich Jan 09 '20 at 22:08
  • This is great, because it creates a `Person` object for each record that you are tracking in. The `OrderByDescending` takes the guesswork out of who has top marks, but the downside is that it doesn't consider ties, but will return the first Name from the input (stable sorted). – Sunny Patel Jan 09 '20 at 22:10
  • 1
    @SunnyPatel Yes, I prefer to separate the processing from the input whenever possible. It would be fairly easy to work with ties as well, depending on how you wanted it handled it would likely just be a slightly more complex LINQ query. – Robert McKee Jan 10 '20 at 15:44