How best to read a File into List

后端 未结 10 1233
盖世英雄少女心
盖世英雄少女心 2020-11-27 17:34

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         


        
相关标签:
10条回答
  • 2020-11-27 17:58
    //this is only good in .NET 4
    //read your file:
    List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();
    
    //manipulate data here
    foreach(string line in ReadFile)
    {
        //do something here
    }
    
    //write back to your file:
    File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);
    
    0 讨论(0)
  • 2020-11-27 17:59
    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;
                }
            }   
            ...
    } 
    
    0 讨论(0)
  • 2020-11-27 18:04
    List<string> lines = new List<string>();
     using (var sr = new StreamReader("file.txt"))
     {
          while (sr.Peek() >= 0)
              lines.Add(sr.ReadLine());
     }
    

    i would suggest this... of Groo's answer.

    0 讨论(0)
  • 2020-11-27 18:05

    You can simple read this way .

    List<string> lines = System.IO.File.ReadLines(completePath).ToList();
    
    0 讨论(0)
提交回复
热议问题