Reputation: 9119
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..
Upvotes: 0
Views: 1204
Reputation: 59645
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)
{
}
Upvotes: 3
Reputation: 65426
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.
Upvotes: 0
Reputation: 12934
Something like this:
foreach (KeyValuePair<string, HtmlInputImage> kvp in smartPenImageDictionary)
{
Console.WriteLine("Value " + kvp.Value);
}
Upvotes: 1
Reputation: 1499800
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.)
Upvotes: 0
Reputation: 798476
Iterating over a dictionary results in KeyValuePair<>
s. Simply access the Key
and Value
members of the appropriate variable.
Upvotes: 1