Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary enumeration in C#

How do I enumerate a dictionary?

Suppose I use foreach() for dictionay enumeration. I can't update a key/value pair inside foreach(). So I want some other method.

like image 282
Ravi Avatar asked Mar 24 '09 10:03

Ravi


People also ask

Is Dictionary an enum?

Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key). An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.

What is an enumeration in C#?

In the C# language, enum (also called enumeration) is a user-defined value type used to represent a list of named integer constants. It is created using the enum keyword inside a class, structure, or namespace. It improves a program's readability, maintainability and reduces complexity.

What is enumeration in C# explain with example?

C# Enumeration An enumeration is used in any programming language to define a constant set of values. For example, the days of the week can be defined as an enumeration and used anywhere in the program. In C#, the enumeration is defined with the help of the keyword 'enum'.

What is dictionary collection?

noun. the act of collecting. something that is collected; a group of objects or an amount of material accumulated in one location, especially for some purpose or as a result of some process: a stamp collection;a collection of unclaimed hats in the checkroom;a collection of books on Churchill.


1 Answers

To enumerate a dictionary you either enumerate the values within it:

Dictionary<int, string> dic;  foreach(string s in dic.Values) {    Console.WriteLine(s); } 

or the KeyValuePairs

foreach(KeyValuePair<int, string> kvp in dic) {    Console.WriteLine("Key : " + kvp.Key.ToString() + ", Value : " + kvp.Value); } 

or the keys

foreach(int key in dic.Keys) {     Console.WriteLine(key.ToString()); } 

If you wish to update the items within the dictionary you need to do so slightly differently, because you can't update the instance while enumerating. What you'll need to do is enumerate a different collection that isn't being updated, like so:

Dictionary<int, string> newValues = new Dictionary<int, string>() { 1, "Test" }; foreach(KeyValuePair<int, string> kvp in newValues) {    dic[kvp.Key] = kvp.Value; // will automatically add the item if it's not there } 

To remove items, do so in a similar way, enumerating the collection of items we want to remove rather than the dictionary itself.

List<int> keys = new List<int>() { 1, 3 }; foreach(int key in keys) {    dic.Remove(key); } 
like image 123
Ian Avatar answered Sep 24 '22 03:09

Ian