How to iterate a C# dictionary

The following snippet shows an easy way to iterate a C# dictionary:


            Dictionary<int, string> dictionary = new Dictionary<int, string>();

            dictionary.Add(1, "Cat");
            dictionary.Add(2, "Dog");
            dictionary.Add(3, "Horse");

            foreach (var item in dictionary)
            {
                // do stuff with item
                Console.WriteLine(string.Format("{0} - {1}", item.Key, item.Value));
            }

            // Result:
            // 1 - Cat
            // 2 - Dog
            // 3 - Horse
This entry was posted in .NET and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>