Jan 27
To iterate over an IDictionary<x,y> interface, use the KeyValuePair<x,y> structure. Following is a simple example:
using System; using System.Collections.Generic; namespace CSharp411 { class Program { static void Main( string[] args ) { IDictionary<string, int> rights = new Dictionary<string, int>(); rights.Add( "Drive", 16 ); rights.Add( "Vote", 18 ); rights.Add( "Drink", 21 ); foreach (KeyValuePair<string,int> right in rights) { Console.WriteLine( "Right={0}, Age={1}", right.Key, right.Value ); } Console.ReadLine(); } } }
This example produces the following output:
Right=Drive, Age=16
Right=Vote, Age=18
Right=Drink, Age=21
[…] Sort C# Array in Descending/Reverse Order Clean/Strip/Remove Binary Characters from C# String Read more… Share and […]
Haven’t seen a more obvious post in this blog yet ;p
Follow you alot but this post just doesn’t make sense, every beginning programmer should know how to use the foreach statement. That you mention the type there is just normal.
Keep up your normal work ))
@Julian: It’s obvious to me too, but a friend of mine is just now learning C# and was stumped by the difference between Dictionary and IDictionary and how KeyValuePair is used for iteration. Most things seem obvious when you’ve known them for a decade, but it’s an interesting experience for me to see him struggling with the language and seemingly easy issues like this one that cause him trouble.
I just started following your blog.
While Julian is correct, this is simple, it is still useful. I have never actually used the IDictionary class and I am in no way a C# newbie (as I have been deving in C# for the past three years).
While this post seems simple, it effectively teaches both the foreach loop and the use of IDictionary object. I now am thinking of all the times I wrote my own class when IDictionary would have worked just as well.
Never underestimate the usefulness of a simple post.