I have declared a dictionary like this:
Dictionary<string, KeyValuePair<string, string>> dc = new Dictionary<string, KeyValuePair<string, string>>();
now how can I loop through it? I wanted something like the following so I created that dictionary:
name1 oldValue1 newValue1
name2 oldValue2 newValue2
...
2 Answers 2
You can loop through it like so
foreach (var pair in dc)
{
string name = pair.Key;
string oldValue = pair.Value.Key;
string newValue = pair.Value.Value;
// use the values
}
But I have a feeling you're using the wrong tool for the job. It sounds to me like you really need to go ahead and define a proper class to hold the names and values, and then just work with a List<T>
of that class.
5 Comments
Tuple<>
is similar to the problem with the Dictionary
approach. If you're using it inside a method as an implementation detail and nobody ever has to see it, maybe you go ahead and use it. If you start passing it around for use by other methods, it's definitely time to give it the class treatment, so that it can self-document what it contains. tuple.Item1
and tuple.Item2
tells me nothing. theClass.Name
and theClass.SomeValue
tells me quite a lot..Item1
and .Item2
or the .Key
, .Value.Key
, .Value.Value
. Don't be hesitant to use classes, even for the "trivial" things.foreach( KeyValuePair<string, string> kvp in dc )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
When you loop a dictionary you use KeyValuePair that is generic. Since your dictionary contain the key as string and the value as string, this one will take also a string for both.
You can access the key with kvp.Key
and the value with kvp.Value
.
For your example, you are using a Dictionary of string that contain a value of KeyValuePair. So, you can have the exact print you want with :
foreach( KeyValuePair<string, KeyValuePair<string,string>> kvp in dc )
{
Console.WriteLine(kvp.Key + " " + kvp.Value.Key + " "+ kvp.Value.Value);
}
Tuple
instead of aKeyValuePair
. But that's just me.KeyValuePair
to store an old value of something in the key and the new value in value.Tuple<string, string>
instead ofKeyValuePair<>
(unless clearly you are recycling the KeyValuePair of another dictionary)struct Replacement<T> { public T OldValue { get; private set; } public T NewValue { get; private set; } ...
and use that? I once spent several hours debugging code where some bozo had decided to store left, top, width and height of a rectangle in a struct with fields named left, top, right, bottom because he was too lazy to define a struct with the correct names. It was extremely difficult to debug because half the names were wrong.