Dom Beasley
Dom Beasley

Reputation: 1

Output scores in a text file in ascending order C#

string[] Entry = *File path*
                        var orderedEntries = Entry.OrderBy(x => int.Parse(x.Split(" ")[1]));
                        foreach (var score in orderedEntries)
                        {
                            Console.WriteLine(Entry);
                        }

I have a text file with the following format: Name Highscore (The name is an inputted string and the highscore is a calculated integer) What I want to happen is that the program outputs all of the names and high scores, ordered by their scores so the highest score is outputted first. I found this code in an answer to a similar question but when I run it, it outputs "System.String[]" instead of the actual entries.

Apologies if this is a slight duplicate, couldn't find anything that I could use to help me in this situation.

Upvotes: 0

Views: 266

Answers (2)

Ali Mardan
Ali Mardan

Reputation: 167

try this:

var orderedEntries = Entry.Select(x => new {name = x.Split(' ')[0], highscore = int.Prase(x.Split(' ')[1])}).OrderByDescending(x => x.highscore));
foreach (var entry in orderedEntries)
{
     Console.WriteLine($"name={entry.name} highscore={entry.highscore}");
}

Upvotes: 0

Hans Kilian
Hans Kilian

Reputation: 25589

I can't see any code to read the contents of the file. I'd try something like

string[] entries = File.ReadAllLines("filename.txt");
var orderedEntries = entries.OrderBy(x => int.Parse(x.Split(" ")[1]));
foreach (var entry in orderedEntries)
{
    Console.WriteLine(entry);
}

This works if the score is the second word in each line. If it's the first, you need to use int.Parse(x.Split(" ")[0].

Upvotes: 2

Related Questions