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

编程入门 行业动态 更新时间:2024-10-10 23:21:12
本文介绍了将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文件转换为字典&lt; string,string&gt;

本文发布于:2023-11-12 12:59:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581564.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字典   文件   txt   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!