C# Dictionary foreach with Examples

How to iterate through a Dictionary in C# with foreach

This tutorial explains how to iterate over a Dictionary in C# using the foreach statement. The foreach statement can be used to iterate over key and value, only key, only value, etc. You can also get the index in the iteration process.

If you are interested in how to iterate over a Dictionary in C# using foreach, please take a look.

Learn more:

Basic iteration

This section shows how to iterate through a Dictionary in C# using foreach. Let's take a look at the sample code:

  1. using System;
  2. using System.Collections.Generic;
  3. namespace CSharpExample
  4. {
  5. class Program
  6. {
  7. static void Main(string[] args)
  8. {
  9. //Initiliazing a dictionary
  10. Dictionary<string, string> books = new Dictionary<string, string>
  11. {
  12. {"ID01", "Title 01"},
  13. {"ID02", "Title 02"},
  14. {"ID03", "Title 03"},
  15. {"ID04", "Title 04"},
  16. };
  17. Console.WriteLine("Obtaining keys and values:");
  18. //Obtaining keys and values
  19. foreach (KeyValuePair<string, string> book in books)
  20. {
  21. Console.WriteLine("Key: {0}, Value: {1}", book.Key, book.Value);
  22. }
  23. Console.WriteLine("Obtaining only keys:");
  24. //Obtaining keys
  25. foreach (string key in books.Keys)
  26. {
  27. Console.WriteLine("Key: {0}", key);
  28. }
  29. Console.WriteLine("Obtaining only values:");
  30. //Obtaining values
  31. foreach (string value in books.Values)
  32. {
  33. Console.WriteLine("Value: {0}", value);
  34. }
  35. }
  36. }
  37. }

The execution results are as follows:

Obtaining keys and values:
Key: ID01, Value: Title 01
Key: ID02, Value: Title 02
Key: ID03, Value: Title 03
Key: ID04, Value: Title 04
Obtaining only keys:
Key: ID01
Key: ID02
Key: ID03
Key: ID04
Obtaining only values:
Value: Title 01
Value: Title 02
Value: Title 03
Value: Title 04

Obtaining the index

When iterating through a Dictionary in C# with foreach, here is how to get the index. Let's take a look at the sample code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace CSharpExample
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. //Initiliazing a dictionary
  11. Dictionary<string, string> books = new Dictionary<string, string>
  12. {
  13. {"ID01", "Title 01"},
  14. {"ID02", "Title 02"},
  15. {"ID03", "Title 03"},
  16. {"ID04", "Title 04"},
  17. {"ID05", "Title 05"},
  18. };
  19. Console.WriteLine("Obtaining keys, values, and index:");
  20. //Obtaining keys, values, and index
  21. var items = books.Select((Entry, Index) => new { Entry, Index });
  22. foreach (var item in items)
  23. {
  24. Console.WriteLine("Index: {0}, Key: {1}, Value: {2}", item.Index, item.Entry.Key, item.Entry.Value);
  25. }
  26. }
  27. }
  28. }

Output:

Obtaining keys, values, and index:
Index: 0, Key: ID01, Value: Title 01
Index: 1, Key: ID02, Value: Title 02
Index: 2, Key: ID03, Value: Title 03
Index: 3, Key: ID04, Value: Title 04
Index: 4, Key: ID05, Value: Title 05

Deletion in the iterative process

In C#, what happens when an element is deleted while iterating through a Dictionary with foreach?

When the above is executed, System.InvalidOperationException is raised. Deletion or other operations are not allowed during the iterative process of the collection.

To solve this, convert the Dictionary keys to a List, iterate through the List with foreach, and delete the Dictionary elements. Let's take a look at the sample code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace CSharpExample
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. //Initiliazing a dictionary
  11. Dictionary<string, string> books = new Dictionary<string, string>
  12. {
  13. {"ID01", "Title 01"},
  14. {"ID02", "Title 02"},
  15. {"ID03", "Title 03"},
  16. {"ID04", "Title 04"},
  17. {"ID05", "Title 05"},
  18. };
  19. foreach (string key in books.Keys)
  20. {
  21. //Remove if key = ID03
  22. if (key == "ID03")
  23. {
  24. books.Remove(key);
  25. }
  26. }
  27. foreach (KeyValuePair<string, string> book in books)
  28. {
  29. Console.WriteLine("Key: {0}, Value: {1}", book.Key, book.Value);
  30. }
  31. }
  32. }
  33. }
  34.  

Output:

Key: ID01, Value: Title 01
Key: ID02, Value: Title 02
Key: ID04, Value: Title 04
Key: ID05, Value: Title 05

Updating in the iterative process

In C#, here is how to update a Dictionary with foreach. Let's take a look at the sample code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace CSharpExample
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. //Initiliazing a dictionary
  11. Dictionary<string, string> books = new Dictionary<string, string>
  12. {
  13. {"ID01", "Title 01"},
  14. {"ID02", "Title 02"},
  15. {"ID03", "Title 03"},
  16. {"ID04", "Title 04"},
  17. {"ID05", "Title 05"},
  18. };
  19. foreach (string key in books.Keys.ToList())
  20. {
  21. //Update if key = ID04
  22. if (key == "ID04")
  23. {
  24. books[key] = "Title 40";
  25. }
  26. }
  27. foreach (KeyValuePair<string, string> book in books)
  28. {
  29. Console.WriteLine("Key: {0}, Value: {1}", book.Key, book.Value);
  30. }
  31. }
  32. }
  33. }

Output:

Key: ID01, Value: Title 01
Key: ID02, Value: Title 02
Key: ID03, Value: Title 03
Key: ID04, Value: Title 40
Key: ID05, Value: Title 05

Summary

I hope you enjoyed this tutorial on how to iterate over a Dictionary in C# using foreach. The foreach loop can be used to iterate over keys and values, only keys, only values. You can also use iteration to obtain an index.

Back to a list of C# tutorials


See also:
C# List Contains with Examples
C# typeof with Examples
C# TryParse (int, double, float) with Examples
C# Data Types
C# Variables