简体   繁体   English

从文本文档C#添加到字典中

[英]Adding to the dictionary from a text document C#

I need to read from the text document through =, line by line, and add it to the dictionary. 我需要通过=逐行从文本文档中读取内容,并将其添加到字典中。 Can you help me please? 你能帮我吗?

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]);
        }
    }
}

For simple text file read operation you can use something like this : 对于简单的文本文件读取操作,您可以使用如下代码:

Note : Make sure your Keys are unique, otherwise you will get the - 注意: 请确保您的密钥是唯一的,否则您将获得-

System.ArgumentException: An item with the same key has already been added. 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);
    }

You can read all lines of file with File.ReadAllLines and after splitting every line into Key & Value add it into dictionary like the following code: 您可以使用File.ReadAllLines读取文件的所有行,并将每一行拆分为键和值后,将其添加到字典中,如下所示:

caution: it may ignore some lines without throwing any exception and it may throw Argument Exception “Item with Same Key has already 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]));

btw the .ForEach method made a lot of garbage (in large lists) and if there is no duplicate keys you can use following: 顺便说一句, .ForEach方法造成了大量垃圾(在大型列表中),如果没有重复的键,则可以使用以下命令:

var slovarik = lines.Select(line=>line.Split('='))
    .Where(line=>line.Length ==2)
    .ToDictionary(line[0],line[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM