C# Dictionary

The Dictionary class is defined in the System.Collections.Generics namespace. It stores the key-value pair and implements the Implements IDictionary<TKey, TValue> interface. The key in a Dictionary is unique and can never be null. The result will not be sorted by keys, unlike the SortedList Collection.

Create a Dictionary

To create a Dictionary with an int key and string value pair, use <int, string>. Set the type in angular braces as shown below:

Let us now see an example of creating a Dictionary in C# with string elements:

Output

Remove all the keys and values

To remove all the keys and values from a Dictionary, use the Clear() method. Let us see an example:

Output

Display only the keys

Use the Keys property to display only the keys from a Dictionary in C#. Let us see an example:

Output

Display only the values

Use the Values property to display only the values from a Dictionary in C#. Let us see an example:

Output

Check the Dictionary for a specific key

The ContainsKey() method allows you to check a Dictionary for a key. Let us see an example:

Output

Check the Dictionary for a specific value

The ContainsValue() method allows you to check a Dictionary for a value. Let us see an example:

Output


Read More

C# - Installation and Setup
C# vs Java - Difference
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading