How best to read a File into List<string>

jacknad picture jacknad · Aug 1, 2011 · Viewed 151.4k times · Source

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);

Answer

Evan Mulawski picture Evan Mulawski · Aug 1, 2011
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;
            }
        }   
        ...
}