gemArt
gemArt

Reputation: 43

How to update a c# dictionary where key is set, value is empty in nested foreach loop

just learning c# so I want to know why my code isn't working as well as any helpful input on how to make this easier. This is just part of a little tool I'm trying to write that will take two files and put them together to build a .json file so I thought to start with a dictionary object. Thank you!

I have 2 text files, one has the list of dictionary keys, the other dictionary values. I want to combine those two text files into one dictionary object but for some reason it's populating the key correctly but the value's are all the same, the last one in the list. So it gets to the bottom of the list of keys and then since it's on the last key value it just repeats the last value for all keys. For example:

txt file 1:
one
two
three

txt file 2:
peach
lime
mango

output:
one, mango
two, mango
three, mango

I want:
one, peach
two, lime
three, mango

This is my code:

        try
        {
            string path1 = @"C:\temp\langVars.txt";
            string path2 = @"C:\temp\langValues.txt";

            string[] readVars = File.ReadAllLines(path1);
            string[] readVals = File.ReadAllLines(path2);

            Dictionary<string, string> dictionaryVars = new Dictionary<string, string>();
            foreach (string s1 in readVars)
            {
                dictionaryVars.Add(s1, "");
                foreach (string s2 in readVals)
                    dictionaryVars[s1] = (s2);
            }
            foreach (KeyValuePair<string, string> kvp in dictionaryVars)
            {
                Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value);
            }

Upvotes: 0

Views: 312

Answers (1)

Sweeper
Sweeper

Reputation: 271175

You should not use a nested foreach loop here:

foreach (string s1 in readVars)
{
    dictionaryVars.Add(s1, "");
    foreach (string s2 in readVals)
        dictionaryVars[s1] = (s2);
}

A nested foreach loop means that you are doing dictionaryVars[s1] = (s2); for each s2 there is, for the same s1. That is:

dictionaryVars["one"] = "peach";
dictionaryVars["one"] = "lime";
dictionaryVars["one"] = "mango";
dictionaryVars["two"] = "peach";
dictionaryVars["two"] = "lime";
dictionaryVars["two"] = "mango";
dictionaryVars["three"] = "peach";
dictionaryVars["three"] = "lime";
dictionaryVars["three"] = "mango";

So you would end up with all three keys having the value mango.

You are also printing the key value pairs from another dictionary called dictionary, rather than dictionaryVars.

You should use a single for loop that iterates both arrays at the same time:

for (int i = 0 ; i < readVars.Length ; i++) {
    dictionaryVars.Add(readVars[i], readVals[i]);
}

And print the contents of dictionaryVars instead:

foreach (KeyValuePair<string, string> kvp in dictionaryVars) // <--- here!
{
    Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value);
}

Upvotes: 2

Related Questions