2013-11-23 44 views
2

到現在爲止,我知道2的方式來獲取文件的一些線(包含約30.000線)按順序在文件中獲取行的最佳方法是什麼?

int[] input = { 100, 50, 377, 15, 26000, 5000, 15000, 30, ... }; 
string output = ""; 
for (int i = 0; i < input.Length; i++) 
{ 
    output += File.ReadLines("C:\\file").Skip(input[i]).Take(1).First(); 
} 

string[] lines = File.ReadAllLines("C\\file"); 

int[] input = { 100, 50, 377, 15, 26000, 5000, 15000, 30, ... }; 
string output = ""; 
for (int i = 0; i < input.Length; i++) 
{ 
    output += lines[input[i]]; 
} 

行我想不需要通過是爲了輸入數組。

第一種方式,我不需要做lines array,其中包含30.000元(〜4MB),但我必須輸入的re-open file for each element

第二種方式,我只需要read file one time,但必須有make an array大數據。

有什麼方法可以讓線條更好?謝謝!

+0

也許使用流將導致您找到一個更具擴展性的解決方案? –

+1

說實話,我沒有看到第二個選項的錯誤,讀取整個文件.4mb不是一個大文件,只要內存在使用後釋放,那麼我會用這種方式。 – Andrew

回答

3

您可以創建緩衝的迭代器,它會遍歷序列只有一次,並保持所需大小的緩衝區:

public class BufferedIterator<T> : IDisposable 
{ 
    List<T> buffer = new List<T>(); 
    IEnumerator<T> iterator; 

    public BufferedIterator(IEnumerable<T> source) 
    { 
     iterator = source.GetEnumerator(); 
    } 

    public T GetItemAt(int index) 
    { 
     if (buffer.Count > index) // if item is buffered 
      return buffer[index]; // return it 
     // or fill buffer with next items 
     while(iterator.MoveNext() && buffer.Count <= index)   
      buffer.Add(iterator.Current); 
     // if we have read all file, but buffer has not enough items 
     if (buffer.Count <= index) 
      throw new IndexOutOfRangeException(); // throw 

     return buffer[index]; // otherwise return required item 
    } 

    public void Dispose() 
    { 
     if (iterator != null) 
      iterator.Dispose(); 
    } 
} 

用法:

var lines = File.ReadLines("C\\file"); 
using (var iterator = new BufferedIterator<string>(lines)) 
{ 
    int[] input = { 100, 50, 377 }; 
    for(int i = 0; i < input.Length; i++) 
     output += iterator.GetItemAt(input[i]); 
} 

利用該樣本僅第一行377的文件將被讀取並緩衝,文件線將僅進行一次計數。

+0

謝謝!你的解決方案比我的更好。一個問題:下面的答案建議我使用流讀取器。如果我使用它,然後將偏移量移動到我需要的行,是隻讀取輸入[]中的行並重要,更快? (我是C#的新手,所以我不知道哪個更好)。 – Sakura

+1

內存流只是Stream類,它將所有數據保存在數組中。當您需要使用流時,它非常有用,但您不想使用文件,網絡或其他流資源。它不能更快​​,然後讀取項目數組和索引數組,因爲它保持陣列內部 –

+1

好吧,感謝您的幫助!接受答案:) – Sakura

相關問題