Search code examples
c#filereaderstreamreader

Best way to read data and store from file?


I have a text file which stores data in this manner:

Player name: NAME HERE
Speed: 7
Strength: 9
Stamina: 4
Player name: ANOTHER NAME HERE
Speed: 5
Strength: 8
Stamina: 3

The same file contains about fifteen different players, and I want to gather values from each of them, store in a temporary race variable, then calculate the mean value of the speed strength and stamina and present a winner. My first idea was to use regular expression but I am currently investigating if there are another, more sustainable way to do this.

This is for a side project of mine and any help is welcome. Thanks


Solution

  • Define your Race Class Structure:

    public class Race
    {
        public string Name;
        public int Speed;
        public int Strength;
        public int Stamina;
    }
    

    Read your data in from your text file, and instantiate your Race objects and collect them into a List<Race>. Once collected you can call Average() from your List to get your results.

    string[] myTextFileLines = File.ReadAllLines(myTextFile);
    
    List<Race> myRaces = new List<Race>();
    for (int i = 0; i < myTextFileLines.Length; i += 4)
    {
        myRaces.Add(new Race()
                        {
                            Name = myTextFileLines[i].Substring(myTextFileLines[i].IndexOf(":") + 2),
                            Speed = Convert.ToInt32(myTextFileLines[i + 1].Substring(myTextFileLines[i + 1].IndexOf(":") + 2)),
                            Strength = Convert.ToInt32(myTextFileLines[i + 2].Substring(myTextFileLines[i + 2].IndexOf(":") + 2)),
                            Stamina = Convert.ToInt32(myTextFileLines[i + 3].Substring(myTextFileLines[i + 3].IndexOf(":") + 2)),
                        });
    }
    
    Console.WriteLine("Avg Speed: {0}", myRaces.Average(r => Convert.ToDouble(r.Speed)));
    Console.WriteLine("Avg Strength: {0}", myRaces.Average(r => Convert.ToDouble(r.Strength)));
    Console.WriteLine("Avg Stamina: {0}", myRaces.Average(r => Convert.ToDouble(r.Strength)));
    Console.ReadLine();
    

    Results (using the exact data you provided in your question):

    enter image description here