Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to read a File into List<string>

I am using a list to limit the file size since the target is limited in disk and ram. This is what I am doing now but is there a more efficient way?

readonly List<string> LogList = new List<string>(); ... var logFile = File.ReadAllLines(LOG_PATH); foreach (var s in logFile) LogList.Add(s); 
like image 210
jacknad Avatar asked Aug 01 '11 20:08

jacknad


People also ask

How do I read a text file into a list?

You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain character.

How do you read a file in Python and store it in a list?

Use str. split() to read a file to a list and str. join() to write a list to a file. Call open(file, mode) with mode as "r" to open the file named file for reading.


2 Answers

A little update to Evan Mulawski answer to make it shorter

List<string> allLinesText = File.ReadAllLines(fileName).ToList()

like image 23
Ram Avatar answered Sep 23 '22 00:09

Ram


var logFile = File.ReadAllLines(LOG_PATH); var logList = new List<string>(logFile); 

Since logFile is an array, you can pass it to the List<T> constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.

Actual constructor implementation:

public List(IEnumerable<T> collection) {         ...         ICollection<T> c = collection as ICollection<T>;         if( c != null) {             int count = c.Count;             if (count == 0)             {                 _items = _emptyArray;             }             else {                 _items = new T[count];                 c.CopyTo(_items, 0);                 _size = count;             }         }            ... }  
like image 76
Evan Mulawski Avatar answered Sep 25 '22 00:09

Evan Mulawski