JAVA Tutorial For Beginners & Experts: Learn In 1 Days - ACTE
Dictionary Collection In C ACTE

Dictionary Collection in C# | Ultimate Guide to Learn [NEW & UPDATED]

Last updated on 28th Jan 2022, Blog, Tutorials

About author

Jagan Mohan (Senior C# Developer )

Jagan Mohan is a Senior Senior C# Developer and has extensive knowledge in the following areas: WPF, XML, REST, Agile, V Model, C#, SQL Server, Web API, ASP, and.NET.

(5.0) | 19741 Ratings 1498
    • Introduction
    • C# Dictionary
    • Which is faster dictionary or Hash table?
    • Which is better dictionary or Dictionary in C#?
    • When would it be advisable for me to involve a word reference in C#?
    • Application Setup
    • Constructors in Dictionary Collection
    • Features
    • C# Dictionary with Examples
    • Methods in Dictionary Collection
    • Dictionary Characteristics
    • Creating a Dictionary
    • The distinction between a Hash table and Dictionary
    • Scope
    • Erasing components from Dictionary
    • What are the advantages of word reference in C#?
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction :-

      C# Dictionary class is a nonexclusive assortment of keys and values pair of information. The Dictionary class is characterized in the System.Collections.A nonexclusive namespace is a conventional class and can store any information type in a type of keys and values. Each critical should be exceptional in the assortment.

      Before you utilize the Dictionary class in your code, you should import the System.Collections.Generic namespace utilizing the accompanying line. utilizing System.Collections.Generic;


      C# Dictionary :-

      A word reference additionally called an affiliated exhibit, is an assortment of one-of-a-kind keys and an assortment of values, where each key is related with one worth. Recovering and adding values is extremely quick. Word references take more memory because for each worth there is additionally a key.


      Which is faster dictionary or Hash table?

      Word reference is an assortment of keys and values in C#. … Word reference is a nonexclusive kind and returns a mistake on the off chance that you attempt to observe a key that isn’t there. The Dictionary assortment is quicker than Hashtable because there is no boxing and unpacking.


      Which is better dictionary or Dictionary in C#?

      The bigger the dictionary, the more it takes. The Dictionary on a fundamental level has a quicker query with O (1) while the query execution of a List is an O(n) activity. The Dictionary map a key to a worth and can’t have copy keys, while a dictionary simply holds back an assortment of values.


      When would it be advisable for me to involve a word reference in C#?

      Whenever your Index of a List must be significant and is novel, you could involve a Dictionary for better lookup tasks. You use Dictionary<'TKey, TValue'> when you want to store values with some novel keys related to them, and getting to them by that key is helpful for you.


      Application Setup :-

      First, we’ll require a record. How about we make an organizer called phonebook with the records PhoneBook.csproj and PhoneBook.cs. Add the accompanying code:

        • PhoneBook.cs
        • utilizing System;
        • utilizing System.Collections.Generic;
        • class PhoneBook
        • {
        • public static Dictionary<'string, string'> phoneNumbers = new Dictionary<'string, string'>();
        • static void Main()
        • {
        • }
        • }

       Dictionary Collection in C#
      Dictionary Collection in C#

      Constructors in Dictionary Collection :-

      The various constructors and their portrayal is given as follows: Table: Constructors in Dictionary Collection in C#


        Constructors
        Description
        Dictionary<'TKey,TValue'>() This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
        Dictionary<'TKey,TValue'>(IDictionary<'TKey,TValue'>) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that contains elements copied from the specified IDictionary<'TKey,TValue'> and uses the default equality comparer for the key type.
        Dictionary<'TKey,TValue'>(IDictionary<'TKey,TValue'>, IEqualityComparer<'TKey'>) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that contains elements copied from the specified IDictionary<'TKey,TValue'> and uses the specified IEqualityComparer<'T'>
        Dictionary<'TKey,TValue'>(IEqualityComparer<'TKey'>) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<'T'>.
        Dictionary<'TKey,TValue'>(Int32) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.
        Dictionary<'TKey,TValue'>(Int32, IEqualityComparer<'TKey'>) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<'T'>.
        Dictionary<'TKey,TValue'>(SerializationInfo, StreamingContext) This constructor initializes a new instance of the Dictionary<'TKey,TValue'> class with serialized data.

      Features :-

    • C# Dictionary initializers
    • C# Dictionary count components
    • C# Dictionary add, eliminate components
    • C# Dictionary ContainsKey and ContainsValue strategies
    • C# navigate word reference
    • C# sort word reference
    • C# SortedDictionary
    • C# Dictionary of Lists

    • Course Curriculum

      Learn Advanced C and C Plus Plus Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      C# Dictionary with Examples :-

      In C#, Dictionary is a nonexclusive assortment that is by and large used to store key/esteem sets. The working of Dictionary is very like the non-nonexclusive hashtable. The benefit of Dictionary is, it is a conventional sort. Word reference is characterized under System.Collection.Generic namespace. It is dynamic implies the size of the word reference is becomes as per the need.


      Significant Points:

    • The Dictionary class executes the
    • IDictionary<'TKey,TValue'> Interface
    • IReadOnlyCollection<'KeyValuePair'><'TKey,TValue'>> Interface
    • IReadOnlyDictionary<'TKey,TValue'> Interface
    • IDictionary Interface
    • In Dictionary, the key can’t be invalid, however worth can be.
    • In Dictionary, the key should be remarkable. Copy keys are not permitted if you attempt to utilize the copy key, the compiler will toss a special case.
    • In Dictionary, you can store the same kinds of components.
    • The limit of a Dictionary is the number of components that Dictionary can hold.

    • Methods in Dictionary Collection :-

      The different methods and their description is given as follows: Table: Methods in Dictionary Collection in C#:


        Methods
        Description
        Add(TKey, TValue) This method adds the specified key and value to the dictionary.
        Clear() This method removes all keys and values from the Dictionary<'TKey,TValue'>.
        ContainsKey(TKey) This method determines whether the Dictionary<'TKey,TValue'> contains the specified key.
        ContainsValue(TVa lue) This method determines whether the Dictionary<'TKey,TValue'> contains a specific value.
        Equals(Object) This method determines whether the specified object is equal to the current object.
        GetEnumerator() This method returns an enumerator that iterates through the Dictionary<'TKey,TValue'>
        GetHashCode() This method serves as the default hash function.
        GetObjectData(SerializationInfo, StreamingContext) This method implements the ISerializable interface and returns the data needed to serialize the Dictionary<'TKey,TValue'> instance.
        GetType() This method gets the Type of the current instance.
        MemberwiseClone() This method creates a shallow copy of the current Object.
        OnDeserialization(Object) This method implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
        Remove(TKey) This method removes the value with the specified key from the Dictionary<'TKey,TValue'>.
        ToString() This method returns a string that represents the current object.
        TryGetValue(TKey, TValue This method gets the value associated with the specified key.

      Dictionary Characteristics :-

    • Dictionary<'TKey, TValue'> stores key-esteem sets.
    • Goes under System.Collections.Generic namespace.
    • Executes IDictionary<'TKey, TValue'> interface.
    • Keys should be exceptional and can’t be invalid.
    • Values can be invalid or copied.
    • Values can be gotten to bypassing related keys in the indexer for example myDictionary[key]
    • Components are put away as KeyValuePair<'TKey, TValue'> objects.

    • Creating a Dictionary :-

      You can make the Dictionary<'TKey, TValue'> object bypassing the kind of keys and values it can store. The accompanying model tells the best way to make a word reference and add key-esteem sets.

      Model: Create Dictionary and Add Elements

        • IDictionary<'int, string'> numberNames = new Dictionary<'int, string'>();
        • numberNames.Add(1,”One”);//adding a key/esteem utilizing the Add() strategy
        • numberNames.Add(2,”Two”);
        • numberNames.Add(3,”Three”);
        • //The accompanying tosses run-time special case: key previously added.
        • //numberNames.Add(3, “Three”);
        • foreach(KeyValuePair<'int, string'> kvp in numberNames)
        • Console.WriteLine(“Key: {0}, Value: {1}”, kvp.Key, kvp.Value);
        • //making a word reference utilizing assortment initializer language structure
        • var urban communities = new Dictionary<'string, string'>(){
        • {“UK”, “London, Manchester, Birmingham”},
        • {“USA”, “Chicago, New York, Washington”},
        • {“India”, “Mumbai, New Delhi, Pune”}
        • };
        • foreach(var kvp in urban communities)
        • Console.WriteLine(“Key: {0}, Value: {1}”, kvp.Key, kvp.Value);

      The distinction between a Hash table and Dictionary :-

      The fundamental contrast between a Hashtable and Dictionary is that while the previous is un-composed and requires boxing and un-boxing upward, the last option doesn’t as it is composed. There is one more distinction between them. On the off chance that you utilize an indexer to recover a worth from a Hashtable occasion and the thing doesn’t exist, you would be returned an invalid worth. In actuality, if you attempt to recover a non-existent thing from a Dictionary example, a special case will be tossed. Note that neither Hashtable nor Dictionary would ensure protecting the request for the things in the assortment.


      While the Hashtable is a feebly composed information structure, a Dictionary is a specific one. The decision between a Hashtable and Dictionary relies upon whether you want a sort of safe assortment. By and large, a Dictionary is a decent decision. To lay it out plainly, a Dictionary is a superior Hashtable. I now and again use Dictionary over a Hashtable.


      Scope :-

      Notice the phone numbers word reference is proclaimed external any strategies. This is to guarantee it has the right extension. Since it’s put right inside our PhoneBook class, strategies pronounced in this class will want to allude to it. Assuming it was inside another class, strategies from this class wouldn’t have the option to get to it. A static variable like this is likewise here and there alluded to as a class variable since it is checked to the level of the class. While static factors can be extremely valuable, we should possibly utilize them assuming the factors should be gotten to wherever in the class. Any other way, we should attempt to scope our factors all the more locally within techniques.


      Course Curriculum

      Get JOB Oriented C and C Plus Plus Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Erasing components from Dictionary :-

      A component can be erased from the Dictionary utilizing the Remove() technique. This technique erases the key, esteem pair with the particular key that is given.


      Tracking down a component in Dictionary:

      The ContainsKey() technique finds assuming that a key is available in the Dictionary or not. Assuming that it is available, ContainsKey() returns TRUE and in any case, it gets back FALSE. Also, ContainsValue() finds assuming a worth is available in the Dictionary or not. Assuming it is available, ContainsValue() returns TRUE and in any case, it gets back FALSE.


      How to look at the accessibility of components in the Dictionary?

      In Dictionary, you can check whether the given key or worth presenting in the predefined word reference or not. The Dictionary<'TKey, TValue'> class gives two unique techniques to checking and the strategies are:

    • ContainsKey: This technique is utilized to check whether the Dictionary<'TKey, TValue'> contains the predefined key.
    • ContainsValue: This strategy is utilized to check whether the Dictionary<'TKey, TValue'> contains a particular worth.

    • Model:

        • // C# program to delineate how
        • // to take a look at the given key or
        • // esteem present in the word reference
        • // or then again not
        • utilizing System;
        • utilizing System.Collections.Generic;
        • class GFG {
        • // Principle Method
        • static public void Main () {
        • // Making a word reference
        • // utilizing Dictionary<'TKey,TValue'> class
        • Dictionary<'int, string'> My_dict =
        • new Dictionary<'int, string'>();
        • // Adding key/esteem sets in the
        • // Word reference Using Add() technique
        • My_dict.Add(1123, “Welcome”);
        • My_dict.Add(1124, “to”);
        • My_dict.Add(1125, “GeeksforGeeks”);
        • // Utilizing ContainsKey() technique to check
        • // the predetermined key is available or not
        • if (My_dict.ContainsKey(1122)==true)
        • {
        • Console.WriteLine(“Key is found…!!”);
        • }
        • else
        • {
        • Console.WriteLine(“Key isn’t found…!!”);
        • }
        • // Utilizing ContainsValue() strategy to check
        • // the predefined esteem is available or not
        • if (My_dict.ContainsValue(“GeeksforGeeks”)==true)
        • {
        • Console.WriteLine(“Value is found…!!”);
        • }
        • else
        • {
        • Console.WriteLine(“Value isn’t found…!!”);
        • }
        • }
        • }
        • Yield:
        • The key isn’t found…!!
        • Esteem is found…!!

      What are the advantages of word reference in C#?

      Fundamentally, a Dictionary<'TKey, TValue'> contains a conventional assortment of key/esteem sets. You can exploit the Add technique for the Dictionary class to store objects in a Dictionary occasion. A Dictionary is quicker than a Hashtable as it dispenses with the boxing and un-boxing overheads


       The advantages of word reference in C#
      The advantages of word reference in C#
      C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion :-

    • The worry, however, is that we need to utilize the indexer to snatch the worth at each recognize in the assortment.? Since we want the worth in every area, this technique is less effective.
    • There may be a utilization situation where this checks out, maybe one where each worth in the assortment isn’t required, yet be careful about the presentation of exceptionally enormous assortments utilizing this methodology.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free