简体   繁体   中英

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.

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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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