How to iterate a C# dictionary

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

</p>
<p>            Dictionary<int, string> dictionary = new Dictionary<int, string>();</p>
<p>            dictionary.Add(1, "Cat");<br />
            dictionary.Add(2, "Dog");<br />
            dictionary.Add(3, "Horse");</p>
<p>            foreach (var item in dictionary)<br />
            {<br />
                // do stuff with item<br />
                Console.WriteLine(string.Format("{0} - {1}", item.Key, item.Value));<br />
            }</p>
<p>            // Result:<br />
            // 1 - Cat<br />
            // 2 - Dog<br />
            // 3 - Horse</p>
<p>

This entry was posted in .NET and tagged , , . Bookmark the permalink.