GTTools.com

06 Jan

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

Leave a Reply

© 2010 GTTools.com | Entries (RSS) and Comments (RSS)

GPS Reviews and news from GPS Gazettewordpress logo