Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Iterating and Modifying Dictionaries | Dictionaries and Key-Value Collections
C# Lists & Collections

bookIterating and Modifying Dictionaries

Working with dictionaries in C# often requires iterating through all the key-value pairs to process or display their contents. The most common and efficient way to do this is by using a foreach loop with the KeyValuePair<TKey, TValue> structure. This approach lets you access both the key and value for each entry in the dictionary.

To traverse a dictionary, you write a foreach loop that iterates over the dictionary variable directly. Each iteration gives you a KeyValuePair, which has Key and Value properties. This is especially useful when you need to process or display both the keys and their associated values.

You may also need to modify dictionary values during iteration. While you can update the value for an existing key by assigning a new value to that key, you must be careful when removing entries while iterating, as this can cause runtime errors if not handled properly.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324
using System; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Dictionary<string, int> ages = new Dictionary<string, int>() { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 35 } }; foreach (KeyValuePair<string, int> entry in ages) { Console.WriteLine($"Name: {entry.Key}, Age: {entry.Value}"); } } } }

When you need to update the value for an existing key in a dictionary, you can assign a new value to that key using the indexer syntax. For example, if you want to change Bob's age, you write ages["Bob"] = 26; and the value is updated.

However, removing items from a dictionary while iterating over it can cause an exception, because the collection is being modified during enumeration. To safely remove items, you should first collect the keys you want to remove in a separate list, and then remove them after finishing the iteration. This approach prevents modification of the dictionary while it is being traversed, ensuring your code runs without errors.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223242526272829303132333435363738394041
using System; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Dictionary<string, int> scores = new Dictionary<string, int>() { { "Anna", 80 }, { "Brian", 55 }, { "Clara", 40 }, { "David", 95 } }; List<string> toRemove = new List<string>(); foreach (KeyValuePair<string, int> entry in scores) { if (entry.Value < 60) { toRemove.Add(entry.Key); } } foreach (string key in toRemove) { scores.Remove(key); } Console.WriteLine("Scores after removal:"); foreach (var entry in scores) { Console.WriteLine($"{entry.Key}: {entry.Value}"); } } } }

1. What is the correct way to iterate over a dictionary in C#?

2. How do you update the value for an existing key?

3. Fill in the blanks to print all keys in a Dictionary<int, string>.

question mark

What is the correct way to iterate over a dictionary in C#?

Select the correct answer

question mark

How do you update the value for an existing key?

Select the correct answer

question-icon

Fill in the blanks to print all keys in a Dictionary<int, string>.

key in items.){     Console.WriteLine(key); }
1
2
3
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 2

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

bookIterating and Modifying Dictionaries

Desliza para mostrar el menú

Working with dictionaries in C# often requires iterating through all the key-value pairs to process or display their contents. The most common and efficient way to do this is by using a foreach loop with the KeyValuePair<TKey, TValue> structure. This approach lets you access both the key and value for each entry in the dictionary.

To traverse a dictionary, you write a foreach loop that iterates over the dictionary variable directly. Each iteration gives you a KeyValuePair, which has Key and Value properties. This is especially useful when you need to process or display both the keys and their associated values.

You may also need to modify dictionary values during iteration. While you can update the value for an existing key by assigning a new value to that key, you must be careful when removing entries while iterating, as this can cause runtime errors if not handled properly.

Program.cs

Program.cs

copy
123456789101112131415161718192021222324
using System; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Dictionary<string, int> ages = new Dictionary<string, int>() { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 35 } }; foreach (KeyValuePair<string, int> entry in ages) { Console.WriteLine($"Name: {entry.Key}, Age: {entry.Value}"); } } } }

When you need to update the value for an existing key in a dictionary, you can assign a new value to that key using the indexer syntax. For example, if you want to change Bob's age, you write ages["Bob"] = 26; and the value is updated.

However, removing items from a dictionary while iterating over it can cause an exception, because the collection is being modified during enumeration. To safely remove items, you should first collect the keys you want to remove in a separate list, and then remove them after finishing the iteration. This approach prevents modification of the dictionary while it is being traversed, ensuring your code runs without errors.

Program.cs

Program.cs

copy
1234567891011121314151617181920212223242526272829303132333435363738394041
using System; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static void Main(string[] args) { Dictionary<string, int> scores = new Dictionary<string, int>() { { "Anna", 80 }, { "Brian", 55 }, { "Clara", 40 }, { "David", 95 } }; List<string> toRemove = new List<string>(); foreach (KeyValuePair<string, int> entry in scores) { if (entry.Value < 60) { toRemove.Add(entry.Key); } } foreach (string key in toRemove) { scores.Remove(key); } Console.WriteLine("Scores after removal:"); foreach (var entry in scores) { Console.WriteLine($"{entry.Key}: {entry.Value}"); } } } }

1. What is the correct way to iterate over a dictionary in C#?

2. How do you update the value for an existing key?

3. Fill in the blanks to print all keys in a Dictionary<int, string>.

question mark

What is the correct way to iterate over a dictionary in C#?

Select the correct answer

question mark

How do you update the value for an existing key?

Select the correct answer

question-icon

Fill in the blanks to print all keys in a Dictionary<int, string>.

key in items.){     Console.WriteLine(key); }
1
2
3
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 2
some-alt