将txt文件转换为字典<string,string>

obd*_*dgy 0 c# dictionary file

我有一个文本文件,我需要将所有偶数行放到Dictionary Key和所有偶数行到Dictionary Value.什么是我的问题的最佳解决方案?

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++;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 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);
Run Code Online (Sandbox Code Playgroud)

我们的想法是成对分组所有行.每个组将有两个项目 - 作为第一个项目的键,以及作为第二个项目的值.

在ideone上演示.