Introduction to Dictionary-Based Collections
Introduction to Dictionary-Based Collections
Introduction to Dictionaries
Description
A dictionary is a list of items with the following two rules:
In some cases, in addition to these two rules, the items should (in some cases must) be ordered. To order the items, the keys are used. Because in most cases a dictionary is made of words, the keys are ordered in alphabetical order. A dictionary can also be made of items whose keys are date values. In this case, the items would be ordered in chronological order. Of course, the keys can also be numeric, in which case they would be ordered incrementally.
There are various types of dictionary types of list used in daily life. The word "dictionary" here does not imply the traditional dictionary that holds the words and their meanings in a human language. The concept is applied in various scenarios.
To support dictionary-based collections, the .NET Framework provides various interfaces and classes. The interfaces allow you to create your own dictionary type of collection class. The classes allow you to directly create a dictionary-based collection with an already built-in functionality.
The Keys of a Dictionary
As mentioned already, a dictionary is a list of key-value pairs. To manage the keys of a dictionary, they are stored in an ICollection<T> collection. To give you access to this collection, the dictionary classes are equipped with a property named Keys, which (at the risk of repeating ourselves) is a collection.
Unlike human language-based dictionaries that don't follow some rules, the keys of a dictionary must be distinct. This means that each item of the Keys collection must be unique with regards to the other keys of the same collection.
The Values of a Dictionary
The values are the second parts of a dictionary. To support the values of a dictionary, each dictionary-based class is equipped with a property named Values. Like the Keys counterpart, the Values property is of type ICollection.
The Foundation of a Dictionary as a Collection
To lay a foundation to create and manage dictionaries, the .NET Framework provides an interface named IDictionary. It starts as follows:
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
The IDictionary interface extends the ICollection<> interface: This is primarily the same generic interface we have seen in previous lessons, except that this one uses a parameter type that is a combination of two types, one for a key and one for a value.
Introduction to .NET Dictionaries
To support dictionary-based collections, the .NET Framework provides the Hashtable class. As seen in previously reviewed .NET collections, all dictionary-based classes implement the ISerializable interface, which makes it possible for their lists to be serialized (saved to a medium).
Introduction to Generic Dictionaries
To support the ability to create a generic collection, the .NET Framework provides some dictionary-types of generic classes. From the System.Collections.Generic namespace, to create a dictionary type of collection, you can use the Dictionary<T> class. The System.Collections.Generic.Dictionary<T> class is equivalent to the System.Collections.Hashtable class.
Before using a dictionary-type of collection, you can declare a variable using one of the constructors of the class. If you are writing your code in a class, you can first include the namespace in the top section of the document. Here is an example:
using System.Collections; public class Geometry { public void Create() { Hashtable shapes = new Hashtable(); } }
You can use the class by qualifying its name. Here is an example:
public class Exercise
{
public static void Main()
{
System.Collections.Hashtable fields = new System.Collections.Hashtable();
}
}
If you decide to use the System.Collections.Generic.Dictionary<T> class, when declaring the variable, you must specify the parameter types after the name of the class. Here is an example:
using System.Collections.Generic; public class Exercise { public static void Main() { Dictionary<string, string> customers = new Dictionary<string, string>(); } }
Adding Items to a Dictionary-Based Collection
Introduction
To let you add an item to a dictionary-based collection, the System.Collections.Hashtable class is equipped with a method named Add. The syntax of this method is:
public virtual void Add(object Key, object Value);
In the same way, the System.Collections.Generic.Dictionary<T> class is equipped with a method named Add. Its syntax is:
public void Add(TKey key, TValue value);
As you can see, you must provide the key and the value as the first and second arguments to the method respectively. Both items are declared as Objects. This means that they can be any type.
As mentioned already, an item of a dictionary is in fact a key-value combination. This means that an item of a dictionary is made of two values.
Value Types as Key/Value Pair
Both the key and the value can be value types. Here are examples:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable employees = new Hashtable();
employees.Add(482508, true);
employees.Add(935296, true);
employees.Add(251179, false);
}
}
Remember that if you are using a generic dictionary, you must specify the parameter types. Here is an example:
using System.Collections.Generic; public class Exercise { public static void Main() { Dictionary<int, bool> employees = new Dictionary<int, bool>(); employees.Add(482508, true); employees.Add(935296, true); employees.Add(251179, false); } }
Value Types as Keys and Strings as Values
One side can be a value type while the other is a string (and vice-versa). Here are examples of calling the Add() method where the keys are integers and the values are strings:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable polygons = new Hashtable();
polygons.Add(3, "Triangle");
polygons.Add(4, "Square");
polygons.Add(5, "Pentagon");
polygons.Add(6, "Hexagon");
polygons.Add(7, "Heptagon");
polygons.Add(8, "Octagon");
}
};
Strings as Keys and Values
Both the key and the value can be strings. Here are examples:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable customers = new Hashtable();
customers.Add("G-205-628", "Residential");
customers.Add("H-858-337-T", "Commercial");
customers.Add("L-975-275-M", "Commercial");
customers.Add("K-927-395", "Residential");
}
}
Keys, Values, and Nullity
When calling the Add() method, you must provide a valid Key argument: it cannot be null. For example, the following code would produce an error:
using System.Collections;
public class Geometry
{
public void Create()
{
Hashtable Students = new Hashtable();
Students.Add("Hermine", "Tolston");
Students.Add("Patrick", "Donley");
Students.Add(null, "Hannovers");
}
}
When adding the items to the list, as mentioned in our introduction, each key must be unique: you cannot have two exact keys. Based on this, the following code would not work because, on the third call, a "Patrick" key exists already:
using System.Collections; public class Exercise { public static int Main() { Hashtable Students = new Hashtable(); Students.Add("Hermine", "Tolston"); Students.Add("Patrick", "Donley"); Students.Add("Chrissie", "Hannovers"); Students.Add("Patrick", "Herzog"); } }
If you try adding a key that exists already in the list, the compiler would throw an ArgumentException exception. The above code would produce:
Unhandled Exception: System.ArgumentException: Item has already been added. Key in dictionary: 'Patrick' Key being added: 'Patrick' at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add ) at System.Collections.Hashtable.Add(Object key, Object value) at Exercise.Main() in C:\Users\pkatts\Source\Repos\Consoles\Exercise1\Exercis e1\Exercise.cs:line 12 Press any key to continue . . .
This means that, when creating a dictionary type of list, you must define a scheme that would make sure that each key is unique among the other keys in the list.
Adding an Item Through an Indexer
As seen with all collections classes so far, each dictionary-based class is equipped with an indexed property. Therefore, besides the Add() method, you can use the indexed property to add an item to the collection. To do this, enter the Key in the square brackets of the property and assign it the desired Value. Here is an example:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable customers = new Hashtable();
customers.Add("G-205-628", "Residential");
customers.Add("H-858-337-T", "Commercial");
customers.Add("L-975-275-M", "Commercial");
customers["K-927-395"] = "Residential";
}
}
Adding Values by their Keyed Indexes
You can initialize a dictionary-based list by using the following formula for each key/value pair:
[key] = value
The expression is included in the curly brackets that are used to initialize the variable. If you want to initialize the list with more than one [key] = value combinations, separate them with commas. Here are examples:
using System.Collections.Generic;
public enum Phase { Gas, Liquid, Solid, Unknown }
public class Element
{
public string Symbol { get; set; } = "H";
public string ElementName { get; set; } = "Hydrogen";
public int AtomicNumber { get; set; } = 1;
public double AtomicWeight { get; set; } = 1.008;
public Phase Phase { get; set; } = Phase.Gas;
public Element()
{
}
public Element(int number)
{
AtomicNumber = number;
}
public Element(string symbol)
{
Symbol = symbol;
}
public Element(int number, string symbol, string name, double mass, Phase phase)
{
ElementName = name;
AtomicWeight = mass;
Phase = phase;
AtomicNumber = number;
Symbol = symbol;
}
}
public class Exercise
{
public static void Main()
{
Dictionary<string, Element> elements = new Dictionary<string, Element>()
{
["h"] = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas),
["he"] = new Element(2, "He", "Helium", 4.002602, Phase.Gas),
["li"] = new Element(3, "Li", "Lithium", 6.94, Phase.Solid),
["be"] = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid),
["b"] = new Element(5, "B", "Boron", 10.81, Phase.Solid),
};
return;
}
}
Initializing a Dictionary with Existing Items
If you have a dictionary collection that already contains some values, you can use them to start a new collection. To support this, the dictionary-based collections provide various constructors. If you are using a Hashtable list, you can use the following constructor:
public Hashtable(IDictionary d);
If you are using a generic collection, you can use a constructor like the following:
public Dictionary(IDictionary<TKey, TValue> dictionary);
In either case, in the parentheses of the constructor, pass a collection created from a class that implements the indicated interface. Here is an example for a Hashtable collection:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable customers = new Hashtable();
customers.Add("G-205-628", "Residential");
customers.Add("H-858-337-T", "Commercial");
customers.Add("L-975-275-M", "Commercial");
customers["K-927-395"] = "Residential";
Hashtable clients = new Hashtable(customers);
}
}
Of course, after initializing such a collection, you can add new items to it. Here are examples:
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable customers = new Hashtable();
customers.Add("G-205-628", "Residential");
customers.Add("H-858-337-T", "Commercial");
customers.Add("L-975-275-M", "Commercial");
customers["K-927-395"] = "Residential";
Hashtable clients = new Hashtable(customers);
clients.Add("G-4208-3529", "Government");
clients.Add("G-2720-2483", "Government");
clients.Add("G-7350-8074", "Government");
}
}
Accessing the Items of a Dictionary-Based Collection
A Dictionary Entry
In human language resources, a dictionary entry is a combination of a word and its definition. To support this concept, the System.Collections namespace provides a structure named DictionaryEntry. Each object created from this structure holds a combination of a key/value pair. This makes it possible to use a foreach loop to visit each entry in a collection. To support the foreach loop, the collection classes (which include the System.Collections.Hashtable class) implement the IEnumerable interface. Remember that this interface is equipped with a method named GetEnumerator. In this case, the item is of type DictionaryEntry. It contains a Key and a Value in combination. The formula to follow is:
foreach(DictionaryEntry variable-name in collection-name) statement(s)
Use this formula to access the items of a System.Collections.Hasthtable collection. If you are writing your code in a webpage, remember that (as we have stated in previous lessons), the statement(s) must be included in a body delimited by curly brackets. Here is an example:
using System.Collections; using static System.Console; public class Exercise { public static void Main() { Hashtable customers = new Hashtable(); customers.Add("G-205-628", "Residential"); customers.Add("H-858-337-T", "Commercial"); customers.Add("L-975-275-M", "Commercial"); customers["K-927-395"] = "Residential"; Hashtable clients = new Hashtable(customers); clients.Add("G-4208-3529", "Government"); clients.Add("G-2720-2483", "Government"); clients.Add("G-7350-8074", "Government"); Title = "Customers Records"; WriteLine("Customers Records"); WriteLine("-----------------------------"); foreach (DictionaryEntry entry in clients) WriteLine("{0,-12}: {1}", entry.Key, entry.Value); WriteLine("============================="); return; } }
This would produce:
Customers Records ----------------------------- G-205-628 : Residential L-975-275-M : Commercial G-4208-3529 : Government K-927-395 : Residential G-2720-2483 : Government G-7350-8074 : Government H-858-337-T : Commercial ============================= Press any key to continue . . .
For Each Enumerated Entry
To recognize each item of a generic collection, the System.Collections.Generic namespace provides a structure named KeyValuePair. This structure contains two properties. One property, named Key, represents the key side of a dictionary item. The other property, named Value, represents the value side of a dictionary item. The KeyValuePair structure is equipped with a constructor that holds a key and a value of a dictionary enter:
public KeyValuePair(TKey key, TValue value);
The main, if not the only, purpose of this structure is to allow you to enumerate the entries of a dictionary. To support this, the generic dictionary classes implement the IEnumerable<> interface. This interface uses the same parameter type as the ICollection<> interface. This interface makes it possible to use the foreach loop to visit each entry of the collection. Here is an example:
using static System.Console; using System.Collections.Generic; public enum Phase { Gas, Liquid, Solid, Unknown } public class Element { public string Symbol { get; set; } = "H"; public string ElementName { get; set; } = "Hydrogen"; public int AtomicNumber { get; set; } = 1; public double AtomicWeight { get; set; } = 1.008; public Phase Phase { get; set; } = Phase.Gas; public Element() { } public Element(int number) { AtomicNumber = number; } public Element(string symbol) { Symbol = symbol; } public Element(int number, string symbol, string name, double mass, Phase phase) { ElementName = name; AtomicWeight = mass; Phase = phase; AtomicNumber = number; Symbol = symbol; } } public class Exercise { public static void Main() { Dictionary<string, Element> elements = new Dictionary<string, Element>() { ["h"] = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas), ["he"] = new Element(2, "He", "Helium", 4.002602, Phase.Gas), ["li"] = new Element(3, "Li", "Lithium", 6.94, Phase.Solid), ["be"] = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid), ["b"] = new Element(5, "B", "Boron", 10.81, Phase.Solid), }; Title = "Chemistry"; WriteLine("Chemistry"); WriteLine("====================================================="); WriteLine("Atomic # Symbol Element Name Atomic Weight Phase"); WriteLine("====================================================="); foreach (KeyValuePair<string, Element> atom in elements) { WriteLine(" {0,3} {1,-3} {2,-12} {3,-9} {4}", atom.Value.AtomicNumber, atom.Value.Symbol, atom.Value.ElementName, atom.Value.AtomicWeight, atom.Value.Phase); WriteLine("-----------------------------------------------------"); } return; } }
Locating an Item in a Dictionary
Getting the Value of an Item from its Index
Locating an item in a dictionary type of list consists of looking for either a key, a value, or a combination of the key and value. If you know the key of an item but you want to find a value, you can use the indexed property of the collection class (either the Hashtable or the Dictionary class) to find the value. Here is an example:
using System.Collections;
using static System.Console;
public class Exercise
{
public static int Main()
{
Hashtable polygons = new Hashtable();
polygons.Add(3, "triangle");
polygons.Add(4, "square");
polygons.Add(5, "pentagon");
polygons.Add(6, "hexagon");
polygons.Add(7, "heptagon");
polygons.Add(8, "octagon");
WriteLine("A " + polygons[5] + " is a polygon that has 5 edges.");
WriteLine("==========================================");
return 0;
}
}
This would produce:
A pentagon is a polygon that has 5 edges. ========================================== Press any key to continue . . .
This technique works only if you provide a valid key. If the compiler cannot find the key you provided, it would throw a System.Collections.Generic.KeyNotFoundException exception with the message "The given key was not present in the dictionary. ".
Checking Whether a Dictionary Contains a Certain Key
To let find out whether a dictionary-based collection contains a certain key, the dictionary-based collections classes are equipped with a method named ContainsKey. The syntax for the Hashtable class is:
public virtual bool ContainsKey(Object key);
The syntax for the Dictionary<> class is:
public bool ContainsKey(TKey key);
To look for an item, pass its key as argument to this method. Here is an example:
using static System.Console;
using System.Collections.Generic;
public enum Phase { Gas, Liquid, Solid, Unknown }
public class Element
{
public string Symbol { get; set; } = "H";
public string ElementName { get; set; } = "Hydrogen";
public int AtomicNumber { get; set; } = 1;
public double AtomicWeight { get; set; } = 1.008;
public Phase Phase { get; set; } = Phase.Gas;
public Element()
{
}
public Element(int number)
{
AtomicNumber = number;
}
public Element(string symbol)
{
Symbol = symbol;
}
public Element(int number, string symbol, string name, double mass, Phase phase)
{
ElementName = name;
AtomicWeight = mass;
Phase = phase;
AtomicNumber = number;
Symbol = symbol;
}
}
public class Exercise
{
private static Dictionary<string, Element> elements = new Dictionary<string, Element>()
{
["h"] = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas),
["he"] = new Element(2, "He", "Helium", 4.002602, Phase.Gas),
["li"] = new Element(3, "Li", "Lithium", 6.94, Phase.Solid),
["be"] = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid),
["b"] = new Element(5, "B", "Boron", 10.81, Phase.Solid),
};
public static void Main()
{
Title = "Chemistry";
WriteLine("Chemistry");
Write("Type an atomic symbol: ");
string symbol = ReadLine();
bool found = elements.ContainsKey(symbol.ToLower());
if (found)
WriteLine("There is a chemical element with that symbol.");
else
WriteLine("There ain't no chemical element with that symbol.");
WriteLine("=================================================")
Here is an example of testing the program:
Chemistry Type an atomic symbol: HE There is a chemical element with that symbol. ================================================= Press any key to continue . . .
Checking Whether a Dictionary Contains a Certain Value
To let you find out whether a dictionary contains a particular value, the dictionany-based classes are equipped with a method named ContainsValue. The syntax of the System.Collections.Hashtable.ContainsValue() method is:
public virtual bool ContainsValue(object key);
The syntax of the System.Collections.Generic.Dictionary.ContainsValue() method is:
public bool ContainsValue(TKey key);
To use this method, the compiler must be able to compare the values of the collection. If the values are from value types or strings, the method would work without a problem. If the values are objects (from a class), the class should (must) have an overridden version of the Equals() methood. You can then call the method. Here is an example:
using static System.Console;
using System.Collections.Generic;
public enum Phase { Gas, Liquid, Solid, Unknown }
public class Element
{
public string Symbol { get; set; } = "H";
public string ElementName { get; set; } = "Hydrogen";
public int AtomicNumber { get; set; } = 1;
public double AtomicWeight { get; set; } = 1.008;
public Phase Phase { get; set; } = Phase.Gas;
public Element(int number)
{
AtomicNumber = number;
}
public Element(int number, string symbol, string name, double mass, Phase phase)
{
ElementName = name;
AtomicWeight = mass;
Phase = phase;
AtomicNumber = number;
Symbol = symbol;
}
public override bool Equals(object obj)
{
Element elm = (Element)obj;
if (elm.AtomicNumber.Equals(this.AtomicNumber))
return true;
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class Exercise
{
private static Dictionary<string, Element> elements = new Dictionary<string, Element>()
{
["h"] = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas),
["he"] = new Element(2, "He", "Helium", 4.002602, Phase.Gas),
["li"] = new Element(3, "Li", "Lithium", 6.94, Phase.Solid),
["be"] = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid),
["b"] = new Element(5, "B", "Boron", 10.81, Phase.Solid),
};
public static void Main()
{
Title = "Chemistry";
WriteLine("Chemistry");
Write("Type an atomic number: ");
int number = int.Parse(ReadLine());
bool found = elements.ContainsValue(new Element(number));
if (found)
WriteLine("There is a chemical element with that atomic number.");
else
WriteLine("There ain't no chemical element with that atomic number.");
WriteLine("=================================================");
return;
}
}
Here is an example of running the program:
Chemistry Type an atomic number: 4 There is a chemical element with that atomic number. ================================================= Press any key to continue . . .
Getting the Value of a Key
The ContainsKey() method allows you to only find out whether a dictionary-based collection contains a certain key. One of its shortcomings (this is not really a shortcoming because the method works as it was designed) is that even if it finds the key, it doesn't produce the corresponding value. To let you get the value that corresponds to a key from a collection, the generic dictionary classes are equipped with a method named TryGetValue. Its syntax is:
public bool TryGetValue(TKey key, out TValue value);
When calling this method, the first argument must be the key to look for. If that key is found, the method returns its corresponding value as the second argument. This argument is passed by reference as an out reference. Here is an example:
using static System.Console;
using System.Collections.Generic;
public enum Phase { Gas, Liquid, Solid, Unknown }
public class Element
{
public string Symbol { get; set; } = "H";
public string ElementName { get; set; } = "Hydrogen";
public int AtomicNumber { get; set; } = 1;
public double AtomicWeight { get; set; } = 1.008;
public Phase Phase { get; set; } = Phase.Gas;
public Element()
{
}
public Element(int number, string symbol, string name, double mass, Phase phase)
{
ElementName = name;
AtomicWeight = mass;
Phase = phase;
AtomicNumber = number;
Symbol = symbol;
}
public override bool Equals(object obj)
{
Element elm = (Element)obj;
if (elm.AtomicNumber.Equals(this.AtomicNumber))
return true;
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
public class Exercise
{
private static Dictionary<string, Element> elements = new Dictionary<string, Element>()
{
["h"] = new Element(1, "H", "Hydrogen", 1.008, Phase.Gas),
["he"] = new Element(2, "He", "Helium", 4.002602, Phase.Gas),
["li"] = new Element(3, "Li", "Lithium", 6.94, Phase.Solid),
["be"] = new Element(4, "Be", "Beryllium", 9.0121831, Phase.Solid),
["b"] = new Element(5, "B", "Boron", 10.81, Phase.Solid),
};
public static void Main()
{
Title = "Chemistry";
WriteLine("Chemistry");
Write("Type an element's symbol: ");
string symbol = ReadLine();
Element elm = new Element();
bool found = elements.TryGetValue(symbol.ToLower(), out elm);
if (found)
WriteLine("There is a chemical element with that symbol.");
else
WriteLine("There ain't no chemical element with that symbol.");
WriteLine("=================================================");
return;
}
}
Here is an example of running the program:
Chemistry Type an element's symbol: LI There is a chemical element with that symbol. ================================================= Press any key to continue . . .
Deleting Items from a Dictionary
Removing Items From a Dictionary Type of List
To let you delete one item from a collection, the dictionary-based classes are equipped with a class named Remove. The syntax from the System.Collections.Hashtable class is:
public virtual void Remove(object key);
The syntax from the System.Collections.Generic.Dictionary class is:
public bool Remove(TKey key);
To use this method, pass a valid key as argument. When you pass an argument to this method, the compiler would try to find it. It the key exists, its item would be delete. Here is an example:
using static System.Console;
using System.Collections;
public class Exercise
{
public static void Main()
{
Hashtable customers = new Hashtable();
customers.Add("G-205-628", "Residential");
customers.Add("H-858-337-T", "Commercial");
customers.Add("L-975-275-M", "Commercial");
customers["K-927-395"] = "Residential";
foreach (DictionaryEntry entry in customers)
WriteLine(entry.Key + ": " + entry.Value);
customers.Remove("L-975-275-M");
WriteLine("-------------------------------");
foreach (DictionaryEntry entry in customers)
WriteLine(entry.Key + ": " + entry.Value);
WriteLine("===============================");
return;
}
}
This would produce:
G-205-628: Residential K-927-395: Residential H-858-337-T: Commercial L-975-275-M: Commercial ------------------------------- G-205-628: Residential K-927-395: Residential H-858-337-T: Commercial =============================== Press any key to continue . . .
If the key is not found in the collection, nothing would happen.
Clearing a Dictionary
To let you remove all items from a collection, the dictionary-based classes are equipped with a method named Clear. The syntax for the non-generic classes is:
public virtual void Clear();
Characteristics of Dictionary-Based Collections
A Sorted Dictionary
In human language-based resources, such as dictionaries or the index in the back section of a book, the list is sorted in alphabetical order. In resources that include dates, such as history references, the lists are arranged in chronological order. The dictionary-based classes also support this concept.
Instead of making you create a dictionary class that supports ordering the items, the .NET Framework provide appropriate classes that accompany the classes we have used so far. To let you create a collection whose keys are ordered, the System.Collections namespace provides a class named SortedList. This class behaves like the Hashtable class except that its items are ordered.
To assist you in creating a generic dictionary-type collection where the keys are ordered, the System.Collections.Generic namespace provides two classes named SortedDictionary and SortedList. This means that, to create an ordered dictionary type of collection, you can use either the SortedDictionary<T> or the SortedList<T> class. The System.Collections.Generic.SortedList<T> class is equivalent to the System.Collections.SortedList class. The System.Collections.Generic.SortedDictionary<T> class is equivalent to the System.Collections.Generic.SortedList<T> class with some differences in the way both classes deal with memory management.
Adding an Item to a Sorted Dictionary
To let you add an item to a sorted dictionary, the System.Collections.SortedList class is equipped with a method named Add. Its syntax is:
public virtual void Add(object Key, object Value);
This method is called as seen previously. Whenever a new item is added to a System.Collections.SortedList variable, a System.Collections.Generic.SortedDictionary<> variable, or a System.Collections.Generic.SortedList<> variable, the list is rearranged so the collection can be sorted in either alphabetical or chronological order based on the keys. This means that, if you want your list to be logically arranged by the keys, use one of these sorted class.
The Number of Entries in a Dictionary
To let you get the number of items in a dictionry-based collections, their classes inherit the Count property from the ICollection interface that they implement.
|
||
Previous | Copyright © 2011-2019, FunctionX | Next |
|