本文介绍了将txt文件转换为字典< string,string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个文本文件,我需要将所有偶数行都放在字典密钥和所有甚至行到字典值。什么是我的问题的最佳解决方案? int count_lines = 1; 字典< string,string> stroka = new Dictionary< string,string>(); foreach(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()值);想法是将所有行分组。每个组将只有两个项目 - 第一个项目的关键字,第二个项目的值。
演示在ideone 。
I have a text file and I need to put all even lines to Dictionary Key and all even lines to Dictionary Value. What is the best solution to my problem?
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++; }解决方案
Try this:
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);The idea is to group all lines by pairs. Each group will have exactly two items - the key as the first item, and the value as the second item.
Demo on ideone.
更多推荐
将txt文件转换为字典< string,string>
发布评论