Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through keys and values of an `IDictionary`?

Tags:

c#

idictionary

How would I iterate through the keys and values of an IDictionary if I don't know the concrete types of the keys and values within, therefore want to just treat them as objects?

If I do something like:

foreach(var x in myIDictionary) { ... }

I think x is an object. But how would I get the Key and Value out of it (both typed as objects), as specified in the IDictionaryEnumerator? There isn't an IKeyValuePair without generic parameters is there?

I guess I could loop through the enumerator by hand using MoveNext etc, but I feel like there must be a way to do it with foreach!

like image 560
Joseph Humfrey Avatar asked Mar 24 '17 15:03

Joseph Humfrey


People also ask

How do you iterate through a dictionary?

To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.

Which of the following will be used to traverse the key-value pairs in dictionary?

You can iterate key-value pairs in the dictionary with the items() method. It can also be received as a tuple of (key, value) . The items() method returns dict_items . It can be converted to a list with list() .


1 Answers

You can explicitly specify DictionaryEntry pair type in foreach like this:

foreach (DictionaryEntry x in myIDictionary)

Though you should be sure that it is standard implementation of IDictionary (like Hashtable or Dictionary<TKey, TValue>)

Otherwise it can be literally anything in enumerator.

like image 170
Lanorkin Avatar answered Sep 20 '22 15:09

Lanorkin