views:

55

answers:

5

I want to get use of dictionary items like I do in List generic class, e.g;

foreach(item in ItemList)
{
  item.BlaBla;
}

But in dictionary there s no chance, like e method above...

Dictionary<string, HtmlInputImage> smartPenImageDictionary;

I mean I got to know the key item for the dictionary item.. but what I want, I want to travel from beginning of the list till the end..

+1  A: 

Iterating over a dictionary results in KeyValuePair<>s. Simply access the Key and Value members of the appropriate variable.

Ignacio Vazquez-Abrams
A: 

A dictionary doesn't have a "beginning" and "end" - it's unordered.

However, you can iterate over the keys or the values:

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

foreach (HtmlInputImage image in smartPenImageDictionary.Values)
{
    ...
}

or key/value pairs:

foreach (KeyValuePair<string, HtmlInputImage> pair in smartPenImageDictionary)
{
    string key = pair.Key;
    HtmlInputImage image = pair.Value;
    ...
}

(Or course var makes the last case rather nicer.)

Jon Skeet
+1  A: 

Something like this:

foreach (KeyValuePair<string, HtmlInputImage> kvp in smartPenImageDictionary)
{
   Console.WriteLine("Value " + kvp.Value);
}
Veer
A: 

I assume you want them in order, the same way an IList<T> provides. As far as I know there is no order guaranteed for a Dictionary<Tkey,TValue>, so you'll need to

mydictionary.ToList();

However as you add and remove items, or even call this again it may change. One solution is to write your own Collection that has a custom indexer you can use.

Chris S
+2  A: 

I am not absolutely sure what you want to achieve but here are the common things you can do with a dictionary.

IDictionary<Int32, String> dictionary = new Dictionary<Int32, String>();

// Iterate over all key value pairs.
foreach (KeyValuePair<Int32, String> keyValuePair in dictionary)
{
    Int32  key = keyValuePair.Key;
    String value = keyValuePair.Value;
}

// Iterate over all keys.
foreach (Int32 key in dictionary.Keys)
{
    // Get the value by key.
    String value = dictionary[key];
}

// Iterate over all values.
foreach (String value in dictionary.Values)
{
}
Daniel Brückner
danke Daniel. !
blgnklc