Conforms array in C # with key string

1

I have the following problem, I want to make a array in C # where the key is a string and then separate the key from the value with a foreach in php as the array the following way Eg:

$array['key_name'] = "value1";

I searched a bit on the Internet and found the following:

    var datos = new Dictionary<string, string>();
    datos ["fondo"] = "LA9018-58-896.png";
    datos ["codigo"] = "LA9018";

and to extract the value it would only be like this:

string aValue = datos["fondo"];
  

What I get

LA9018-58-896.png

The problem I have is that I only bring a single key and what I want is to do it dynamically with a foreach . Saving in one variable the key and in another the value .

    
asked by Yoel Rodriguez 07.06.2017 в 22:44
source

1 answer

2

In C # the arrays always have numerical indexes.

What you are creating is a'Dictionary 'object in which each element is a key-value pair, in your case both of type string.

You can traverse the elements of the Dictionary object with a foreach as you do in php. Each element obtained in the iteration will be a key-value pair, so that you can access the key through the Key property and the value through the Value property:

        var datos = new Dictionary<string, string>
        {
            ["fondo"] = "LA9018-58-896.png",
            ["codigo"] = "LA9018"
        };

        foreach (var item in datos)
        {
            Debug.WriteLine($"{item.Key}: {item.Value}");
            // Tratamiento del elemento item
        }
    
answered by 07.06.2017 / 23:21
source