简体   繁体   中英

C# Dictionary how to read key=value from file

Im a student first year and I am trying to read a big report file with the Dictionary class. My report has the following format:

Key=value
Key=value
.
.
. 

Now, Dictionary needs 2 inputs for the key and the value, but how am I going to fill this in? I imagine that it works with a loop but I am just too inexperience and how to get some answers here.

It is not a duplicate because I try something different. I want to read .WER reports which already contain the said format. I don't want a already filled Dictionary. I need to fill it.

foreach loop with Add()

var result = new Dictionary<string, string>();

foreach (string line in report)
{
    string[] keyvalue = line.Split('=');
    if (keyvalue.Length == 2) 
    { 
        result.Add(keyvalue[0], keyvalue[1]);
    }
}

Linq-approach

Dictionary<string,string> result = File.ReadAllLines(@"C:\foo.txt")
                                       .Select(x => x.Split('='))
                                       .ToDictionary(x => x[0], x => x[1]);

[Original poster wrote:] For people in the future who have this problem, this is how I did it now with help:

Dictionary<string, string> _werFileContent = new Dictionary<string, string>();

using (StreamReader sr = new StreamReader(Path))
{
    string _line;
    while ((_line = sr.ReadLine()) != null)
    {
        string[] keyvalue = _line.Split('=');
        if (keyvalue.Length == 2)
        {
            _werFileContent.Add(keyvalue[0], keyvalue[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