zstaylor zstaylor - 26 days ago 17
C# Question

How to save data from an array

I'm making a simple application to save school grades and displays it back to you when requested. How can I save this data so you do not have to reenter it every time the application is run?

Answer

Split problem into lesser ones:

  • How would you like to save an item to string in a file
  • How would you like to read (parse) an item from a string (line) of the file?

in case school grades are just ints:

int[] grades = new int[] {2, 3, 4, 5, 2};

the answers for the questions above can be item.ToString() and int.Parse(line) and so you can put

File
  .WriteAllLines(@"C:\MyData.txt", grades
  .Select(grade => grade.ToString()));

And

int[] grades = File
  .ReadLines(@"C:\MyData.txt")
  .Select(line => int.Parse(line))
  .ToArray();
Comments