使用LINQ从配置文件中读取键值对 [英] Using LINQ to read key value pair from configuration file

查看:90
本文介绍了使用LINQ从配置文件中读取键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些密钥对值的文件

I have a file with some key pair values

key1 = value1
key2 = value2

[section name]
key3 = value3
key4 = value4

所以我不在乎节名,因为键是唯一的.我只想获取输入键的值.我要阅读以下内容.

so I don't care about section names as the keys are unique. I just want to get the the value for an input key. I have the following to read the lines.

  var userDataLines = File.ReadAllLines(pathToFile);

我有这样的东西

 var result = userDataLines.Select(userDataLine => userDataLine.Split(new[] { '=' }))
                           .Where(split => split.Length == 2);

为我提供了一个集合中的所有键值对.

gives me all the key value pairs in one collection.

但是本质上我想从我的文件中获得一个包含键和值的字典,但是不确定如何做到这一点.有人可以朝我正确的方向打枪吗?

but essentially I want to get a dictionary with keys and values from my file but not sure how to do that. Can anyone poing me in the right direction?

谢谢

推荐答案

您可以使用(小改进:使用 ReadLines 代替 ReadAllLines ,然后将每行分成

(Small improvements: use ReadLines instead of ReadAllLines, and split each line into at most 2 parts.)

这篇关于使用LINQ从配置文件中读取键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆