Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
logo
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

Dictionary in C#

In this article, we will learn about the dictionaries in C#.

A dictionary is a collection of keys and values.

The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.

Creating a Dictionary

We create a Dictionary C# using the following syntax:
Dictionary<TKey, TValue> dict = new Dictionary<TKey, TValue>();
<TKey> here denotes any datatype of the Key which we want to create a dictionary of.
Similiarly, <TValue> denotes any datatype of the Value


Properties of Dictionary

  • Count: This property gets the number of keys actually contained in the dictionary.
  • Comparer: Determines equality for the keys in the dictionary.
  • Dict[TKey]: Gets or sets the value associated with the specified key.
  • Keys: Gets a collection containing the keys in the Dictionary<TKey,TValue>.
  • Values: Gets a collection containing the values in the Dictionary<TKey,TValue>.

Methods of Dictionary

  • Add(TKey, TValue): Adds the specified key and value to the dictionary.
  • ContainsKey(TKey): Determines whether the Dictionary<TKey,TValue> contains the specified key.
  • ContainsValue(TValue): Determines whether the Dictionary<TKey,TValue> contains a specific value.
  • Remove(TKey): Removes the value with the specified key from the Dictionary<TKey,TValue>.
  • Clear(): Removes all keys and values from the Dictionary<TKey,TValue>.

Dictionary Operation Examples:

Different Dictionary operations are demonstrated in the example below:

using System;
using System.Collections.Generic;
namespace DictionaryDemo {
    class Example {
        static void Main(string[] args) {
            Dictionary < int, int > D = new Dictionary < int, int > ();
            D.Add(5, 1);          
            // D.Add(5, 2); will throw an error
            // because 5 has already been added
            
            D[5] = 2;       
            D[2] = 10;                          // We can use indexing property to add elements
            D[10] = 3;
            Console.WriteLine(D.Count);        // Prints 3 because 5 is only added once in the dictionary
            
            Console.WriteLine(D[5]);            // Prints 2, the last entered value for 5.
            
            Console.WriteLine(D.ContainKey(5));  // Checks if 5 is present
            
            D.Remove(5);                          // Removes 5
            
            Console.WriteLine(D.ContainsKey(5));  // Prints False this time
            
            D[2]++;
            Console.WriteLine(D[2]);            // Prints 11 as we performed an arithmetic operation
                                                // on a value present in a dictionary

            foreach(int i in D.Keys) {          // Prints all the Keys
                Console.Write(i + " ");
            }
            Console.WriteLine();
        }
    }
}

Output:

3

2

True

False

11

2 10

2 5 9


Task

In the editor below, perform the different tasks as directed.

Start solving Dictionary in C# on Interview Code Editor
Hints
  • Complete Solution

Discussion


Loading...
Click here to start solving coding interview questions
Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College you graduated from
College/University Name
Job Title
Job Title
Engineering Leadership
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Security Leadership
Database Administrator
Data Analyst
Data Engineer
Non Coder
Other
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test