What is the best way to iterate the dictionary?

I've seen several different ways to iterate over dictionaries in C. Is there a standard way?

#1 building

foreach(KeyValuePair<string, string> entry in myDictionary)
{
    // do something with entry.Value or entry.Key
}

#2 building

I'll say foreach is the standard way, although it obviously depends on what you're looking for

foreach(var kvp in my_dictionary) {
  ...
}

Is that what you are looking for?

#3 building

If you try to use a general dictionary for images in C, you can use an associative array in another language:

foreach(var item in myDictionary)
{
  foo(item.Key);
  bar(item.Value);
}

Or, if you only need to traverse the collection of keys, use the

foreach(var item in myDictionary.Keys)
{
  foo(item);
}

Finally, if you are only interested in values:

foreach(var item in myDictionary.Values)
{
  foo(item);
}

(note that the var keyword is an optional C 3.0 and later feature, and you can also use the exact type of key / value here.)

#4 building

There are many options. My personal favorite is KeyValuePair

Dictionary<string, object> myDictionary = new Dictionary<string, object>();
// Populate your dictionary here

foreach (KeyValuePair<string,object> kvp in myDictionary)
{
     // Do some interesting things
}

You can also use the keys and values collection

#5 building

Depending on whether you are using a key or a value

From MSDN Dictionary(TKey, TValue) Class description:

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}", 
        kvp.Key, kvp.Value);
}

// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
    openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
    Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
    openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
    Console.WriteLine("Key = {0}", s);
}

Posted by fazbob on Sat, 07 Dec 2019 02:16:12 -0800