2013-06-02 32 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()); 
     } 
    } 
} 

这样你会得到一本字典,如果你有奇数行,最后一个条目将有一个空值。

相关问题