| What is Dictionary in C# Generic Collections
The simple defination for Dictionary in C# is just like English dictionary which is collection of words with there defination which is listed alphabetically. Now comes to c# dictionary is acollection of keys and Values where key is like the word and values is just like defination.
Dictionary< TKey, TValue> class is a generic collection class in the System.Collection.Generics namespace. Here Tkey is type of key and TValue is type of TValue.
Now comes to declaration part we can assign Dictionary object to a variable of IDictionary< Tkey, TValue> or Dictionary< TKey, Tvalue> class.
Now questions comes how to declare Dictionary. SO below is the syntax
IDictionary< int, string> dictobj = new Dictionary< int, string>();
or
Dictionary< int, string> dictobj = new Dictionary< int, string>();
In above declaration int is the type of key and string is the type of value that will be stored into a dictionary object named dictobj. We need to use valid data type for keys and values.
Now comes to Properties and Methods of IDictionary. There are 5 below property followed by 5 Methods
(1)Count
(2)IsReadOnly
(3)Item
(4)Keys
(5)Values
Now comes to Methods
(1)Add
(2)Remove
(3)ContainsKey
(4)ContainsValue
(5)Clear
(6)TryGetValue
Now comes to different coding part add remove syntax
(1)Add Element into the Dictionary
IDictionary< int, string> dictobj = new Dictionary< int, string>();
dictobj.Add(1,"Java");
dictobj.Add(2,"Dotnet");
dictobj.Add(3,"Sql");
Now some more method to add key values pair is :-
dictobj.Add(new KeyValuePair< int, string>(4, "csharp"));
dictobj.Add(new KeyValuePair< int, string>(5, "testing"));
dictobj.Add(6, "Phython");
We can also initialized using collecton initializer syntax with keys and values as shown below.
IDictionary< int, string> dict = new Dictionary< int, string>()
{
{1,"Silverlight"},
{2, "SAP"},
{3,"XML"}
}; | | |