我有一个文本文件,我需要将所有偶数行放入字典键,将所有偶数行放入字典值。我的问题的最佳解决方案是什么?
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++;
}
尝试这个:
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);
这个想法是将所有线成对分组。每个组将恰好有两个项目 - 第一项为键,第二项为值。
ideone 上的演示 http://ideone.com/eqT8iU.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)