c# read a text file. How to avoid reading it again

  • A+
Category:Languages

I'm new to programming and I have a problem with calling a method.
I read a text file in the first method and saved each line in a list. And the return type of the method was List so that I could bring any specific line of the text file in other method. But the problem is that I have to read the text file over and over whenever I call the first method. I have to call the method more than 100 times and the length of the text file is over 1000 lines.

public static List<double> readLine(int line)  {     //read a text file and save in readList     return readList[line]; }  public static double useList() {     readLine(1);     readLine(2);     readLine(3);     readLine(4);     return 0; } 

 


Like I said in my comment, just read the entire file once and save it into a List<string> using File.ReadAllLines() (Cast the output to a list). Once you have that, then you can just use the List<string> directly without having to go back to read the file each time. See below.

public class Program {     private static List<string> lines;     public static void Main()     {         // At this point lines will have the entire file. Each line in a different index in the list         lines = File.ReadAllLines("..path to file").ToList();          useList(); // Use it however     }      // Just use the List which has the same data as the file     public static string readFromList(int num)     {         return lines[num];     }       public static void useList()     {         string line1 = readFromList(1); // Could even be string line1 = lines[SomeNum];         string line2 = readFromList(2);     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: