Dictionary c example LEARNOVITA

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

Last updated on 12th Aug 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 of WPF, XML, REST, Agile, V model, C#, SQL server, Web API, and ASP.NET.

(5.0) | 18394 Ratings 2091

Introduction :-

C# The lexicon category may be a nonexclusive assortment of keys and values combined with knowledge. The lexicon category is characterized within the System.Collections.A nonexclusive namespace may be a standard category and might store any data sort in an exceedingly style of keys and values. every important ought to be exceptional within the assortment. Before you utilize the lexicon category in your code, you ought to import the System.Collections.Generic namespace utilizing the concomitant line. utilizing System.Collections.Generic;

Which is a quicker lexicon or Hash table?

A word reference to boot referred to as AN attached exhibit, is AN assortment of one-of-a-kind keys ANd an assortment of values, wherever every key’s connected with one value. sick and adding values is extraordinarily fast. Word references take a lot of memory as a result of every value there’s to boot a key.

Which is a quicker lexicon or Hash table?

Word reference is AN assortment of keys and values in C#. … Word reference may be a nonexclusive kind and returns a slip-up on the off likelihood that you just arrange to observe a key that isn’t there. The lexicon assortment is faster than Hashtable as a result of there’s no boxing and unpacking.

Which is best lexicon or lexicon in C#?

The bigger the lexicon, the more it takes. The lexicon on an elementary level features a faster question with O (1) whereas the question execution of an inventory is AN O(n) activity. The lexicon maps a key to a value and can’t have copy keys, whereas a lexicon merely holds back AN assortment of values.

When would it not be better on behalf of me to involve a word reference in C#?

Whenever your Index of an inventory should be vital and is novel, you’ll involve a lexicon for higher search tasks. you employ a lexicon once you need to store values with some novel keys associated with them, and reaching to them by that key is useful for you.

Application Setup :

First, we’ll need a record. however concerning we tend to create AN organizer referred to as telephone directory with the records telephone directory.csproj and telephone directory.cs. Add the concomitant code:

concomitant code

Constructors in wordbook assortment :

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

    ConstructorsDescription
    Dictionary() This builder initializes a replacement instance of the wordbook category that’s empty, has the default initial capability, and uses the default equality comparer for the key kind.
    Dictionary(IDictionary) This builder initializes a replacement instance of the wordbook category that contains parts derived from the desired IDictionary and uses the default equality comparer for the key kind.
    Dictionary(IDictionary, IEqualityComparer) This builder initializes a replacement instance of the wordbook category that contains parts derived from the desired IDictionary and uses the desired IEqualityComparer
    Dictionary(IEqualityComparer) This builder initializes a replacement instance of the wordbook category that’s empty, has the default initial capability, and uses the desired IEqualityComparer.
    Dictionary(Int32) This builder initializes a replacement instance of the wordbook category that’s empty, has the desired initial capability, and uses the default equality comparer for the key kind.
    Dictionary(SerializationInfo, StreamingContext) This builder initializes a replacement instance of the wordbook category with serialized information.

Features :

  • C# lexicon initializers
  • C# lexicon count elements
  • C# lexicon add, eliminate elements
  • C# lexicon ContainsKey and ContainsValue ways
  • C# navigate word reference
  • C# type word reference
  • C# SortedDictionary
  • C# lexicon of Lists

C# lexicon with Examples:

In C#, lexicon may be a nonexclusive assortment that’s by and enormous wont to store key/esteem sets. The operating of a lexicon is extremely just like the non-nonexclusive hashtable. The advantage of lexicon is, it’s a standard type. Word reference is characterized below System.Collection.Generic namespace. its dynamic implies the dimensions of the word reference becomes as per the requirement.

Significant Points:

  • The lexicon category executes the
  • IDictionary Interface
  • IReadOnlyCollection> Interface
  • IReadOnlyDictionary Interface
  • IDictionary Interface
  • In lexicon, the key can’t be invalid, but the value will be.
  • In lexicon, the key ought to be exceptional. Copy keys don’t seem to be permissible if you commit to utilize the copy key, the compiler can toss a special case.
  • In lexicon, you’ll be able to store equivalent forms of elements.
  • The limit of a lexicon is the variety of elements that lexicon will hold.

Methods in lexicon assortment :

The different strategies and their description is given as follows: Table: strategies in lexicon assortment in C#:

    MethodsDescription
    Add(TKey, TValue) This methodology adds the desired key and price to the wordbook.
    Clear() This methodology removes all keys and values from the wordbook.
    ContainsKey(TKey) This methodology determines whether or not the workbook contains the desired key.
    ContainsValue(TVa lue) This methodology determines whether or not the workbook contains a particular price.
    Equals(Object) This methodology determines whether or not the desired object is up to this object.
    GetEnumerator() This methodology returns associate degree functionary that iterates through the wordbook
    GetHashCode() This methodology is the default hash performed.
    GetObjectData(SerializationInfo, StreamingContext) This methodology implements the ISerializable interface and returns the information required to serialize the wordbook instance.
    GetType() This methodology is kind of this instance.
    MemberwiseClone() This methodology creates a shallow copy of this Object.
    OnDeserialization(Object) This methodology implements the ISerializable interface and raises the deserialization event once the deserialization is complete.
    ToString() This methodology returns a string that represents this object.
    Remove(TKey) This methodology removes the worth with the desired key from the wordbook.
    TryGetValue(TKey, TValue) This methodology gets the worth related to the desired key.

Dictionary Characteristics :

  • The dictionary stores key-esteem sets.
  • Goes below System.Collections.Generic namespace.
  • Executes IDictionary interface.
  • Keys ought to be exceptional and can’t be invalid.
  • Values are often invalid or traced.
  • Values are often gotten to bypassing connected keys within the trained worker as an example myDictionary[key]
  • Components square measure place away as KeyValuePair objects.

Creating a workbook :

You will create the workbook object bypassing the type of keys and values it can store. The related model tells the most effective thanks to create a word reference and add key-esteem sets.

Model: produce workbook and Add components

  • IDictionary numberNames = new Dictionary();
  • numberNames.Add(1,”One”);//adding a key/esteem utilizing the Add() strategy
  • numberNames.Add(2,”Two”);
  • numberNames.Add(3,”Three”);
  • //The related tosses run-time special case: key antecedently value-added.
  • //numberNames.Add(3, “Three”);
  • foreach(KeyValuePair kvp in numberNames)
  • Console.WriteLine(“Key: , Value: ”, kvp.Key, kvp.Value);
  • var urban communities = new Dictionary(),
  • ,
  • };
  • foreach(var kvp in urban communities)
  • Console.WriteLine(“Key: , Value: ”, kvp.Key, kvp.Value);

The distinction between a Hash table and lexicon :

The fundamental distinction between a Hashtable and lexicon is that whereas the previous is un-composed and needs boxing and unboxing upward, the last possibility doesn’t because it consists. there’s an additional distinction between them. On the off chance that you simply utilize AN trained worker to recover a value from a Hashtable occasion and also the issue doesn’t exist, you’d be returned an invalid value. genuinely, if you conceive to recover a non-existent issue from a lexicon example, a special case is tossed. Note that neither Hashtable nor lexicon would guarantee protection of the request for the items within the assortment. While the Hashtable could be a feebly composed info structure, a lexicon could be a specific one. The choice between a Hashtable and lexicon depends upon whether or not you would like a form of safe assortment. By and large, a lexicon could be a good call. to get it out plainly, a lexicon could be a superior Hashtable. I currently and once more use lexicon over a Hashtable.

Scope :

Notice the phone numbers word reference is announced external any methods. This is often to ensure it’s the proper extension. Since it’s improved within our telephone directory category, methods pronounced during this category can wish to touch on that. assuming it had been within another category, methods from this category wouldn’t have the choice to induce that. A static variable like this is often likewise here and there alluded to as a category variable since it’s checked to the extent of the category. whereas static factors is extraordinarily valuable, ought to|we should always|we must always} probably utilize them assuming the factors should be gotten to where within the category. the other approach, we should always conceive to scope our factors all the a lot of domestically inside techniques.

Erasing parts from lexicon :

An element is erased from the lexicon utilizing the Remove() technique. this system erases the key, esteem combined with the actual key that’s given.

Tracking down a element in Dictionary:

The ContainsKey() technique finds whether a secret’s obtainable within the lexicon or not. assuming that it’s obtainable, ContainsKey() returns TRUE and in any case, it gets back FALSE. Also, ContainsValue() finds whether a value is offered within the lexicon or not. assuming it’s obtainable, ContainsValue() returns TRUE and in any case, it gets back FALSE.

How to inspect the accessibility of parts within the Dictionary?

In the wordbook, you’ll check whether or not the given key or value is present within the predefined word reference or not. The wordbook category provides 2 distinctive techniques to checking and also the ways are:

ContainsKey: this system is used to see whether or not the workbook contains the predefined key.

ContainsValue: This strategy is used to see whether or not the workbook contains a specific value.

Model:

  • // C# program to delineate however
  • // to require a glance at the given key or
  • // esteem gift within the word reference
  • // or however not
  • utilizing System;
  • utilizing System.Collections.Generic;
  • class GFG technique
  • static public void Main () creating a word reference
  • // utilizing wordbook category
  • Dictionary My_dict =
  • new Dictionary();
  • // Adding key/esteem sets within the
  • // Word reference exploitation Add() technique
  • My_dict.Add(1123, “Welcome”);
  • My_dict.Add(1124, “to”);
  • My_dict.Add(1125, “GeeksforGeeks”);
  • / Utilizing ContainsKey() technique to see
  • // the preset secret’s accessible or not
  • if (My_dict.ContainsKey(1122)==true)
  • else
  • // Utilizing ContainsValue() strategy to see
  • // the predefined esteem is accessible or not
  • if (My_dict.ContainsValue(“GeeksforGeeks”)==true)
  • else
  • }
  • }
  • Yield:
  • The key isn’t found…!!
  • Esteem is found…!!

What square measure the benefits of word reference in C#?

Fundamentally, a lexicon contains a traditional assortment of key/esteem sets. you’ll exploit the Add technique for the lexicon category to store objects during a lexicon occasion. A lexicon is faster than a Hashtable because it dispenses with the boxing and unboxing overheads

Conclusion :

The worry, however, is that we want to utilize the skilled worker to grab the value at every acknowledgement within the assortment.? Since we wish the value in each space, this method is a smaller amount effective. There is also a utilization scenario wherever this checks out, perhaps one wherever every price within the assortment isn’t needed, nevertheless take care concerning the presentation of exceptionally huge assortments utilizing this system.

Are you looking training with Right Jobs?

Contact Us

Popular Courses