2013-06-02 31 views
0

我有一個文本文件,我需要將所有偶數行放到Dictionary Key中,並將所有偶數行放到Dictionary Value中。什麼是我的問題的最佳解決方案?將txt文件轉換爲字典<string,string>

int count_lines = 1; 
Dictionary<string, string> stroka = new Dictionary<string, string>(); 

foreach (string line in ReadLineFromFile(readFile)) 
{ 
    if (count_lines % 2 == 0) 
    { 
     stroka.Add Value 
    } 
    else 
    { 
     stroka.Add Key 
    } 

    count_lines++; 
} 
+2

什麼是鍵值對應關係?行號'2n-1'是關鍵,'2n'是值? – Andrei

回答

2

你可能想這樣做:

var array = File.ReadAllLines(filename); 
for(var i = 0; i < array.Length; i += 2) 
{ 
    stroka.Add(array[i + 1], array[i]); 
} 

這是一個單獨讀取兩個而不是每行步驟的文件。

我想你想使用這些對:(2,1),(4,3),...。如果不是,請更改此代碼以滿足您的需求。

+2

他自己的解決方案是流式傳輸,但是您的解決方案需要在形成字典之前將整個文件加載到內存中。您的解決方案需要兩倍的內存 –

7

試試這個:

var res = File 
    .ReadLines(pathToFile) 
    .Select((v, i) => new {Index = i, Value = v}) 
    .GroupBy(p => p.Index/2) 
    .ToDictionary(g => g.First().Value, g => g.Last().Value); 

的想法是由一羣對所有線路。每個組將有兩個項目 - 第一個項目的關鍵字,第二個項目的值。

Demo on ideone

0
String fileName = @"c:\MyFile.txt"; 
    Dictionary<string, string> stroka = new Dictionary<string, string>(); 

    using (TextReader reader = new StreamReader(fileName)) { 
    String key = null; 
    Boolean isValue = false; 

    while (reader.Peek() >= 0) { 
     if (isValue) 
     stroka.Add(key, reader.ReadLine()); 
     else 
     key = reader.ReadLine(); 

     isValue = !isValue; 
    } 
    } 
1

您可以通過讀取線線,並添加到字典

public void TextFileToDictionary() 
{ 
    Dictionary<string, string> d = new Dictionary<string, string>(); 

    using (var sr = new StreamReader("txttodictionary.txt")) 
    { 
     string line = null; 

     // while it reads a key 
     while ((line = sr.ReadLine()) != null) 
     { 
      // add the key and whatever it 
      // can read next as the value 
      d.Add(line, sr.ReadLine()); 
     } 
    } 
} 

這樣你會得到一本字典,如果你有奇數行,最後一個條目將有一個空值。

相關問題