【问题标题】:Adding to the dictionary from a text document C#从文本文档 C# 添加到字典
【发布时间】:2017-04-27 18:27:02
【问题描述】:
我需要通过 = 逐行读取文本文档,并将其添加到字典中。你能帮帮我吗?
using (StreamReader sr = new StreamReader("slovardata.txt"))
{
string _line;
while ((_line = sr.ReadLine()) != null)
{
string[] keyvalue = _line.Split('=');
if (keyvalue.Length == 2)
{
slovarik.Add(keyvalue[0], keyvalue[1]);
}
}
}
【问题讨论】:
标签:
c#
file
dictionary
add
【解决方案1】:
您可以使用 File.ReadAllLines 读取文件的所有行,并将每一行拆分为 Key & Value 后,将其添加到字典中,如下代码:
注意:它可能会忽略某些行而不抛出任何异常,并且可能会抛出 Argument Exception “Item with Same Key has been added”
var lines = System.IO.File.ReadAllLines("slovardata.txt");
lines.Select(line=>line.Split('='))
.Where(line=>line.Length ==2)
.ToList()
.ForEach(line=> slovarik.Add(line[0],line[1]));
顺便说一句,.ForEach 方法产生了很多垃圾(在大列表中),如果没有重复的键,您可以使用以下方法:
var slovarik = lines.Select(line=>line.Split('='))
.Where(line=>line.Length ==2)
.ToDictionary(line[0],line[1]);
【解决方案2】:
对于简单的文本文件读取操作,您可以使用以下内容:
注意: 确保你的密钥是唯一的,否则你会得到 -
System.ArgumentException: 具有相同键的项目已经被
已添加。
string[] FileContents = File.ReadAllLines(@"c:\slovardata.txt");
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (string line in FileContents)
{
var keyvalue = Regex.Match(line, @"(.*)=(.*)");
dict.Add(keyvalue.Groups[1].Value, keyvalue.Groups[2].Value);
}
foreach (var item in dict)
{
Console.WriteLine("Key : " + item.Key + "\tValue : " + item.Value);
}