tags:

views:

1970

answers:

7

I am using StringDictionary collection to collect Key Value Pairs.

Ex :

        StringDictionary KeyValue = new StringDictionary();
        KeyValue.Add("A", "Load");
        KeyValue.Add("C", "Save");

During retrieval i have to form two foreach to get keys and Values (i.e)

foreach(string key in KeyValue.Values ) { ... }

foreach(string key in KeyValue.Keys) { ... }

is there any way to get the pair in single foreach ?

+6  A: 

You can do a foreach loop on the dictionary, which will give you a DictionaryEntry in each iteration. You can access the Key and Value properties from that object.

foreach (DictionaryEntry value in KeyValue)
{
    // use value.Key and value.Value
}
Fredrik Mörk
+1  A: 

One should be enough:

foreach (string key in KeyValue.Keys)
{
  string value = KeyValue[key];

  // Process key/value pair here
}

Or did I misunderstand your question?

Thorsten Dittmar
What you understand is right! Everybody's answer is working perfectly
+1  A: 

You could use:

foreach(KeyValuePair<string, string> pair in KeyValue) { ... }
Peter van der Heijden
He's asking about StringDictionary - not `Dictionary<string, string>`. StringDictionary doesn't contain `KeyValuePair<string, string>` instances.
Mark Seemann
Yes StringDictionary does not support KeyValuePair,Just tested
Oops! Missed that
Peter van der Heijden
No issue at all,Peter :) Have a nice day
+1  A: 
foreach(DictionaryEntry entry in KeyValue)
{
    // ...
}
Anton Gogolev
+1  A: 

You can simply enumerate over the dictionary itself. It should return a sequence of DictionaryEntry instances.

A better alternative is to use Dictionary<string, string>.

Mark Seemann
Thanks Mark.I will follow.
+3  A: 

The StringDictionary can be iterated as DictionaryEntry items:

foreach (DictionaryEntry item in KeyValue) {
   Console.WriteLine("{0} = {1}", item.Key, item.Value);
}

I would suggest that you use the more recent Dictionary<string,string> class instead:

Dictionary<string, string> KeyValue = new Dictionary<string, string>();
KeyValue.Add("A", "Load");
KeyValue.Add("C", "Save");

foreach (KeyValuePair<string, string> item in KeyValue) {
   Console.WriteLine("{0} = {1}", item.Key, item.Value);
}
Guffa
Sure .I will change the one to Dictionary<string,string>
+2  A: 

You have already many answers. But depending on what you want to do, you can use some LINQ.

Let's say you want to get a list of shortcuts that use the CTRL key. You can do something like:

var dict = new Dictionary<string, string>();
dict.Add("Ctrl+A", "Select all");
dict.Add("...", "...");

var ctrlShortcuts =
    dict
        .Where(x => x.Key.StartsWith("Ctrl+"))
        .ToDictionary(x => x.Key, x => x.Value);
Bruno Reis
Cool ! This one also useful.