-1

I'm currently making a simple game using c# in visual studios for college, atm I have been saving the player name and score to a text file, what I'm looking to to do is sort that text file by highest score and save it again

I've got a basic array to display the outcome in a list box and sorts by name but I want to sort it by the score, if anyone could steer me.in the right direction that be appreciated

private void scoreArray()

{

string[] fileName = File.ReadAllLines(@"E:\College Year 3\Computer Programming 2\Minefield\Leaderboard.txt");

Array.Sort(fileName);

foreach (string score in fileName)

{

listBox1.Items.Add(score);

}

}

The data in the text file is stored as Name score

Loathing
  • 5,109
  • 3
  • 24
  • 35
  • You are sorting by TEXT and numbers will not sort like you expect. When Text the order is 1, 10,100,1000,2,20,200,2000. – jdweng Oct 08 '20 at 17:29
  • Lots of ways. One preferable method is to read your data into an object with separate properties for the separate values in your string, and then sort an array of those. See duplicate. – Peter Duniho Oct 08 '20 at 23:53

2 Answers2

1

File content

James,20
Jake,10
John,1000

code


// object to move data to/from file
public class FileItem
{
    public string Name {get; set;}
    public int Points {get; set;}
    public override string ToString()
    {
        return Name + "," + Points;
    }
}

// read the file
string[] content = File.ReadAllLines(path);
// parse it and store in list of objects
var sortList = new List<FileItem>();
foreach (string line in content)
{
    string[] namePoints = string.Split(",", StringSplitOptions.RemoveEmptyEntries);
    var item = new FileItem() {Name = namePoints[0], Points = int.Parse(namePoints[1])};
    sortList.Add(item);
}

// Sort and write to file
using (StreamWriter outFile= new StreamWriter(path))
{
    foreach (FileItem fileItem in sortList.OrderBy(fi => fi.Points);)
        outputFile.WriteLine(fileItem.ToString());
}

Disclaimer - not tested

T.S.
  • 18,195
  • 11
  • 58
  • 78
  • hey just trying this out now, however there is no var? im using c# windows forms app – adrian rowland Oct 08 '20 at 18:28
  • 1
    @adrianrowland what is the .net framework are you using? `var` is not a data type, its a keyword. introduced in c#3.0 - long ago.... `var item = new FileItem` is same as `FileItem item = new FileItem` – T.S. Oct 08 '20 at 18:46
-1

One way is to use Sort(Array, IComparer) (see https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=netcore-3.1#System_Array_Sort_System_Array_System_Collections_IComparer_ for details).

In your compare function, you would parse out the scores and compare them numerically.

A better way would be to parse your data on load into an array of structures (with name and score).

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27