Dictionary in C# is a generic collection that stores key-value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of a Dictionary is, that it is a generic type. A dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing according to the need.
- Key-Value Pair: The value is stored in the Key-Value pair.
- Efficient Lookup: It provides fast lookups for values based on keys.
- Unique Keys: Stored keys uniquely and adding duplicate keys results in a runtime exception.
Example 1: Creating and Displaying a Dictionary
C#
// C# program to demonstrate how to
// create and display a dictionary
using System;
using System.Collections.Generic;
class Geeks
{
public static void Main()
{
// Creating a dictionary
Dictionary<int, string> sub = new Dictionary<int, string>();
// Adding elements
sub.Add(1, "C#");
sub.Add(2, "Javascript");
sub.Add(3, "Dart");
// Displaying dictionary
foreach (var ele in sub)
{
Console.WriteLine($"Key: {ele.Key}, Value: {ele.Value}");
}
}
}
OutputKey: 1, Value: C#
Key: 2, Value: Javascript
Key: 3, Value: Dart
Steps to Create a Dictionary
The dictionary can be created in different ways using Dictionary Class. Here, we are using the Dictionary<TKey, TValue>() constructor used to create an instance of the Dictionary<TKey, TValue> class by default initial capacity is empty, and uses the default equality comparison for the key type.
Step 1: Include System.Collections.Generic namespace
using System.Collections.Generic;
Step 2: Create a Dictionary using Dictionary<TKey, TValue> class
Dictionary dictionary_name = new Dictionary();
Performing Different Operations on Dictionary
1. Adding Elements
- Add(): This method to add key/value pairs in your Dictionary.
- Collection-Initializer: We can also use a collection initializer to add elements to the dictionary.
- Using Indexers: We can directly add the elements by indexes.
// Using Add method
Dictionary<int, string> dict= new Dictionary<int, string>();
dict.Add(1, "One");
// Using Collection Initializer
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "One" },
{ 2, "Two" }
};
// Using Indexers
Dictionary<int, string> dict = new Dictionary<int, string>();
dict[1] = "One";
dict[2] = "Two";
2. Accessing Elements
The key-value pair of the Dictionary is accessed using three different ways:
Using For Loop: We can use a to access the key-value pairs of the Dictionary.
for(int =0; x< dict.Count; x++)
{
Console.WriteLine("{0} and {1}", dict.Keys.ElementAt(x
dict[ dict.Keys.ElementAt(x)]);
}
Using Index: We can access individual key-value pairs of the Dictionary by using its index value. We can specify the key in the index to get the value from the given dictionary, no need to specify the index. The indexer always takes the key as a parameter
Console.WriteLine("Value is:{0}", dict[1]);
Console.WriteLine("Value is:{0}", dict[2]);
Note: If the given key is not available in the dictionary, then it gives KeyNotFoundException.
Using foreach loop:
foreach (var pair in dict)
Console.WriteLine($"Key: {pair.Key}, Value: {pair.Value}");
Example: Creating and Displaying a Dictionary with Add()
C#
// C# program to illustrate how to
// create a dictionary using Add()
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating a dictionary using Dictionary<TKey,TValue> class
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-Value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Displaying the dictionary
foreach (KeyValuePair<int, string> ele in dict)
{
Console.WriteLine("key: {0} and value: {1}", ele.Key, ele.Value);
}
}
}
Outputkey: 1 and value: Welcome
key: 2 and value: to
key: 3 and value: GeeksforGeeks
3. Removing Elements
In the Dictionary, we are allowed to remove elements from the Dictionary. Dictionary<TKey, TValue> class provides two different methods to remove elements that are:
- Clear: This method removes all keys and values from the Dictionary<TKey, TValue>.
- Remove: This method removes the value with the specified key from the Dictionary<TKey, TValue>.
Example:
C#
// Removing key-value pairs from the dictionary
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating a dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Before Remove() method
foreach (KeyValuePair<int, string> ele in dict)
{
Console.WriteLine("key: {0}, Value: {1}", ele.Key, ele.Value);
}
// Remove a key-value pair
dict.Remove(1);
Console.WriteLine("\nAfter Remove() method:");
foreach (KeyValuePair<int, string> ele in dict)
{
Console.WriteLine("key: {0}, Value: {1}", ele.Key, ele.Value);
}
}
}
Outputkey: 1, Value: Welcome
key: 2, Value: to
key: 3, Value: GeeksforGeeks
After Remove() method:
key: 2, Value: to
key: 3, Value: GeeksforGeeks
4. Checking Element
In Dictionary, we can check whether the given key or value is present in the specified dictionary or not. The Dictionary<TKey, TValue> class provides two different methods which are:
- ContainsKey: This method is used to check whether the Dictionary<TKey, TValue> contains the specified key.
- ContainsValue: This method is used to check whether the Dictionary<TKey TValue> contains a specific value.
Example:
C#
// Checking if a key or value is present in the dictionary
using System;
using System.Collections.Generic;
class Geeks
{
static public void Main()
{
// Creating a dictionary
Dictionary<int, string> dict = new Dictionary<int, string>();
// Adding key-value pairs
dict.Add(1, "Welcome");
dict.Add(2, "to");
dict.Add(3, "GeeksforGeeks");
// Using ContainsKey() to check if the key exists
if (dict.ContainsKey(1))
Console.WriteLine("Key is found...!!");
else
Console.WriteLine("Key is not found...!!");
// Using ContainsValue() to check if the value exists
if (dict.ContainsValue("to"))
Console.WriteLine("Value is found...!!");
else
Console.WriteLine("Value is not found...!!");
}
}
OutputKey is found...!!
Value is found...!!
Important Points
- The Dictionary class implements the interfaces:
- IDictionary<TKey, TValue>
- IReadOnlyCollection<KeyValuePair<TKey,TValue>>
- IReadOnlyDictionary<TKey, TValue and IDictionary
- In theDictionary, the key cannot be null, but the value can be.
- In Duplicate keys are not allowed. If we add a duplicate key then the compiler will throw an exception.
- In the Dictionary, we can only store the same types of elements.
- The capacity of a Dictionary is the number of elements that a Dictionary can hold.
Similar Reads
Introduction
C# TutorialC# (pronounced "C-sharp") is a modern, versatile, object-oriented programming language developed by Microsoft in 2000 that runs on the .NET Framework. Whether you're creating Windows applications, diving into Unity game development, or working on enterprise solutions, C# is one of the top choices fo
4 min read
Introduction to .NET FrameworkThe .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The .NET framework is primarily used on Windows, while .NET Core (which evolved into
6 min read
C# .NET Framework (Basic Architecture and Component Stack)C# (C-Sharp) is a modern, object-oriented programming language developed by Microsoft in 2000. It is a part of the .NET ecosystem and is widely used for building desktop, web, mobile, cloud, and enterprise applications. This is originally tied to the .NET Framework, C# has evolved to be the primary
6 min read
C# Hello WorldThe Hello World Program is the most basic program when we dive into a new programming language. This simply prints "Hello World!" on the console. In C#, a basic program consists of the following:A Namespace DeclarationClass Declaration & DefinitionClass Members(like variables, methods, etc.)Main
4 min read
Common Language Runtime (CLR) in C#The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others.When a C# program is compiled, th
4 min read
Fundamentals
C# IdentifiersIn programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. Example: public class GFG { static public void Main () { int
2 min read
C# Data TypesData types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C# each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given pr
7 min read
C# VariablesIn C#, variables are containers used to store data values during program execution. So basically, a Variable is a placeholder of the information which can be changed at runtime. And variables allows to Retrieve and Manipulate the stored information. In Brief Defination: When a user enters a new valu
4 min read
C# LiteralsIn C#, a literal is a fixed value used in a program. These values are directly written into the code and can be used by variables. A literal can be an integer, floating-point number, string, character, boolean, or even null. Example:// Here 100 is a constant/literal.int x = 100; Types of Literals in
5 min read
C# OperatorsIn C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.Types of Operat
7 min read
C# KeywordsKeywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to be used as variable names or objects. Doing this will result in a compile-time error.Example:C#// C# Program to illustrate the
5 min read
Control Statements
C# Decision Making (if, if-else, if-else-if ladder, nested if, switch, nested switch)Decision Making in programming is similar to decision making in real life. In programming too, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of program based on certain conditions. These
5 min read
C# Switch StatementIn C#, Switch statement is a multiway branch statement. It provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type.
4 min read
C# LoopsLooping in a programming language is a way to execute a statement or a set of statements multiple times, depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops.Types of Loops in C#Loops are mainly divided
4 min read
C# Jump Statements (Break, Continue, Goto, Return and Throw)In C#, Jump statements are used to transfer control from one point to another point in the program due to some specified code while executing the program. In, this article, we will learn to different jump statements available to work in C#.Types of Jump StatementsThere are mainly five keywords in th
4 min read
OOP Concepts
Methods
Arrays
C# ArraysAn array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array spe
8 min read
C# Jagged ArraysA jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows
4 min read
C# Array ClassArray class in C# is part of the System namespace and provides methods for creating, searching, and sorting arrays. The Array class is not part of the System.Collections namespace, but it is still considered as a collection because it is based on the IList interface. The Array class is the base clas
7 min read
How to Sort an Array in C# | Array.Sort() Method Set - 1Array.Sort Method in C# is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method as follows:Sort<T>(T[]) MethodSort<T>(T[], IComparer<T>) MethodSort<T>(T[], Int32, Int32) MethodSort<T>(T[], Comparison<T>) Method
8 min read
How to find the rank of an array in C#Array.Rank Property is used to get the rank of the Array. Rank is the number of dimensions of an array. For example, 1-D array returns 1, a 2-D array returns 2, and so on. Syntax: public int Rank { get; } Property Value: It returns the rank (number of dimensions) of the Array of type System.Int32. B
2 min read
ArrayList
String
Tuple
Indexers