C# Dictionary

WBOY
Release: 2024-09-03 15:31:59
Original
1030 people have browsed it

The Dictionary class in C# is represented as Dictionary which is a collection similar to the dictionary in English comprising of words collections and their definitions listed in alphabetical order in more than one language but the dictionary in C# is comprised of keys and values collection where the key represents the word and value represents the definition. This dictionary class in C# belongs to System.Collection.Generics namespace and is a generic collection class where Tkey represents the key type and Tvalue represents the Tvalue type and the variable of IDictionary class or Dictionary class can be assigned to any object in the dictionary.

The syntax of Dictionary class in C# is as follows:

IDictionary<TKey, TValue> variable_name = new Dictionary<TKey, TValue>();
Copy after login

or

Dictionary<TKey, TValue > variable_name = new Dictionary<TKey, TValue >();
Copy after login

Working of Dictionary class in C#

  • One of the important classes in the System.Collections.Generic namespace is Dictionary class.
  • A generic data structure is represented by the dictionary class in C# which contains data keys and their corresponding values. Hence data of any type can be stored using the instance of a dictionary.
  • The extension of the ICollection interface is the IDictionary interface.
  • The Add method of dictionary class is used to store the objects in the instance of a dictionary.
  • Using a dictionary eliminates the overheads of boxing and unboxing.

Consider the example below to explain the usage of Dictionary class to obtain the keys alone:

using System;
using System.Collections.Generic;
//a class called program is defined
class program
{
// main method is called
public static void Main()
{
// a new dictionary is created with key type string and value type string
Dictionary<string, string> Dict = new Dictionary<string, string>();
// using add method in dictionary to add the objects to the dictionary
Dict.Add("A", "Karnataka");
Dict.Add("B", "Maharashtra");
Dict.Add("C", "Andra");
Dict.Add("D", "TamilNadu");
Dict.Add("E", "Delhi");
Dict.Add("F", "Goa");
// Finding the number of key value pairs in the dictionary
Console.WriteLine("The number of key value pairs in the dictionary are : " + Dict.Count);
// using the property of keys to get the keys alone from the dictionary
Dictionary<string, string>.KeyCollection key =  Dict.Keys;
// a foreach loop is used to loop around every key in the dictionary and to obtain each key value
foreach(string sh in key)
{
Console.WriteLine("The key is referred as = {0}", sh);
}
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

In the above program, the program is the class defined. Then the main method is called. a new dictionary is created with the key type string and value type string. Then using add method in the dictionary to add the objects to the dictionary. Then the number of key-value pairs in the dictionary is found using the count. Then using the property of keys, the keys alone from the dictionary is extracted. Then a foreach loop is used to loop around every key in the dictionary and to obtain each key value. The output of the program is as shown in the snapshot above.

Methods of C# Dictionary

There are several methods in the Dictionary class in C#. They are:

1. Add()

  • The add() method is used to add an item to the collection of the dictionary.
  • The add() method is used to add key-value pairs to the collection of Dictionary.
  • Consider the example below to demonstrate the add method of dictionary class:
using System;
using System.Collections.Generic;
//a class called check is defined
public class Check
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str.Add(3,"Green");
str.Add(1,"Saffron");
str.Add(2,"White");
str.Add(new KeyValuePair<int, string>(4, "Blue"));
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str.Count);
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

2.  Remove()

The Remove() method is used to remove the specified item’s first occurrence from the dictionary.

The remove() method is used to remove an element which is specified along with key from the dictionary object.

Consider the example below to demonstrate the usage of Remove() method in Dictionary class:

using System;
using System.Collections.Generic;
//a class called check1 is defined
public class Check1
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str1 = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str1.Add(3,"Green");
str1.Add(1,"Saffron");
str1.Add(2,"White");
str1.Add(new KeyValuePair<int, string>(4, "Blue"));
str1.Remove(1);
str1.Remove(new KeyValuePair<int, string>(2, "White"));
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str1.Count);
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

3. ContainsKey()

The ContainsKey() method is used to check whether the given key is present in Dictionary

Consider the below program to demonstrate the usage of ContainsKey() method in Dictionary class:

using System;
using System.Collections.Generic;
//a class called2 check is defined
public class Check2
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str2 = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str2.Add(3,"Green");
str2.Add(1,"Saffron");
str2.Add(2,"White");
str2.Add(new KeyValuePair<int, string>(4, "Blue"));
str2.Remove(1);
str2.Remove(new KeyValuePair<int, string>(2, "White"));
Console.WriteLine("If the key 3 is present?{0}", str2.ContainsKey(3));
Console.WriteLine("If the key 2 is present? {0}", str2.Contains(new KeyValuePair<int, string>(2, "White")));
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str2.Count);
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

4. ContainsValue()

The ContainsValue() method is used to check whether the given value is present in Dictionary

Consider the below program to demonstrate the usage of ContainsValue() method in Dictionary class:

using System;
using System.Collections.Generic;
//a class called check3 is defined
public class Check3
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str2 = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str2.Add(3,"Green");
str2.Add(1,"Saffron");
str2.Add(2,"White");
str2.Add(new KeyValuePair<int, string>(4, "Blue"));
str2.Remove(1);
str2.Remove(new KeyValuePair<int, string>(2, "White"));
Console.WriteLine("If the key 3 is present?{0}", str2.ContainsKey(3));
Console.WriteLine("If the key 2 is present? {0}", str2.Contains(new KeyValuePair<int, string>(2, "White")));
//new dictionary of both string key and string value types is defined
Dictionary<string, string> stri = new Dictionary<string, string>();
stri.Add("Flag","Green");
Console.WriteLine("If the value Green is present?{0}", stri.ContainsValue("Green"));
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str2.Count);
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

5. Clear()

The clear() method is used to clear all the objects in the dictionary class.

Consider the below program to demonstrate the usage of ContainsValue() method in Dictionary class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//a class called check4 is defined
public class Check4
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str3 = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str3.Add(3,"Green");
str3.Add(1,"Saffron");
str3.Add(2,"White");
str3.Add(new KeyValuePair<int, string>(4, "Blue"));
str3.Remove(1);
str3.Remove(new KeyValuePair<int, string>(2, "White"));
Console.WriteLine("If the key 3 is present?{0}", str3.ContainsKey(3));
Console.WriteLine("If the key 2 is present? {0}", str3.Contains(new KeyValuePair<int, string>(2, "White")));
//new dictionary of both string key and string value types is defined
Dictionary<string, string> stri1 = new Dictionary<string, string>();
stri1.Add("Flag","Green");
Console.WriteLine("If the value Green is present?{0}", stri1.ContainsValue("Green"));
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str3.Count);
Console.Clear();
}
}
Copy after login

The output of the above program blank as shown in the snapshot below:

C# Dictionary

6. TryGetValue()

The TryGetValue() method checks if the given key exists, if it does not exist it returns false. If the given key exists, it returns true and assigns the given value to the specified key.

Consider the below program to demonstrate the usage of TryGetValue() method of Dictionary class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//a class called check4 is defined
public class Check4
{
//main method is called
public static void Main()
{
//a new dictionary is created with key type int and value type string
IDictionary<int, string> str3 = new Dictionary<int, string>();
//Add method is used to add objects to the dictionary
str3.Add(3,"Green");
str3.Add(1,"Saffron");
str3.Add(2,"White");
str3.Add(new KeyValuePair<int, string>(4, "Blue"));
str3.Remove(1);
str3.Remove(new KeyValuePair<int, string>(2, "White"));
Console.WriteLine("If the key 3 is present?{0}", str3.ContainsKey(3));
Console.WriteLine("If the key 2 is present? {0}", str3.Contains(new KeyValuePair<int, string>(2, "White")));
//new dictionary of both string key and string value types is defined
Dictionary<string, string> stri1 = new Dictionary<string, string>();
stri1.Add("Flag","Green");
Console.WriteLine("If the value Green is present?{0}", stri1.ContainsValue("Green"));
string res;
if(str3.TryGetValue(4, out res))
{
Console.WriteLine("The value of the specified key is {0}", res);
}
else
{
Console.WriteLine("The specified key is not present.");
}
//The number of objects in the dictionary is displayed using count
Console.WriteLine("The number of objects in the given dictionary is: {0} ", str3.Count);
}
}
Copy after login

The output of the above program is as shown in the snapshot below:

C# Dictionary

Conclusion

In this tutorial, we understand the concept of Dictionary class in C# through definition, the syntax of Dictionary class in C#, working of Dictionary class, and their methods through programming examples and their outputs.

The above is the detailed content of C# Dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!