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.

Comments are closed.