2

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.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Roadman1991
  • 169
  • 3
  • 16

2 Answers2

7

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]);
Yola
  • 18,496
  • 11
  • 65
  • 106
fubo
  • 44,811
  • 17
  • 103
  • 137
0

[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]);
        }
    }
}
live2
  • 3,771
  • 2
  • 37
  • 46
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81