Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

343
Visualizações
How to iterate through keys and values of an `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!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

The point you're missing is that there are no guarantees of what the type of the values will be if you iterate an IDictionary. They could be literally anything. The only guarantee is that it implements .GetEnumerator().

If you want to iterate over the contents of the IDictionary, you can iterate over its keys:

foreach (object key in myIDictionary.Keys)
{
    object value = myIDictionary[key];

    // do something with key and value
}

You can also convert your IDictionary to a Dictionary<object, object> to make foreach a bit more friendly:

var myDictionary = myIDictionary.Keys
                                .Cast<object>()
                                .ToDictionary(k => k, k => d[k]);

// kv is a KeyValuePair<object, object>
foreach (var kv in dobj)
{

}

You can even add an extension method to do this for you:

public static Dictionary<object, object> ToDictionary(this IDictionary dict)
{
    return dict.Keys.Cast<object>().ToDictionary(k => k, k => dict[k]);
}


// usage
// kv is a KeyValuePair<object, object>
foreach (var kv in myIDictionary.ToDictionary())
{
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda