本文介绍了使用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?

谢谢

推荐答案

您可以使用 ToDictionary扩展方法如下:

var result = File.ReadLines(pathToFile)
                 .Select(line => line.Split(new[] { '=' }, 2))
                 .Where(split => split.Length == 2)
                 .ToDictionary(split => split[0], split => split[1]);

(小改进:使用 ReadLines 代替 ReadAllLines ,然后将每行分成最多2个部分.)

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

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

08-19 02:50