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 library 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 dictionay 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 dictionay 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 library 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 library provides the Hashtable class.
Introduction to Generic Dictionaries
To support the ability to create a generic collection, the .NET library 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; namespace Exercises.Models { public class Geometry { public void Create() { Hashtable shapes = new Hashtable(); } } }
If you are writing your code in a webpage, you must qualify the class. Here is an example:
@using System.Collections
@{
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 @{ System.Collections.Generic.Dictionary<string, string> customers = new System.Collections.Generic.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
@{
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 @{ Dictionary<int, bool> employees = new Dictionary<int, bool>(); employees.Add(482508, true); employees.Add(935296, true); employees.Add(251179, false); } </body> </html>
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 are integers and the values are strings:
@using System.Collections
@{
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
@{
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");
}
Objects as Values
In a dictionary collection, one side, most likely the key, can be a value type or a string while the other side is an object from a class. Here are examples:
@using System.Collections.Generic @{ Dictionary<int, string> regions = new Dictionary<int, string>(); Dictionary<char, State> states = new Dictionary<char, State>(); regions.Add(1, "Capital"); regions.Add(2, "Central"); State state = new State() { Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" }; states.Add('m', state); state = new State("VE-B", "Barcelona", 16700, 43300, "Anzoátegui"); states.Add('b', state); states.Add('n', new State() { Name = "Monagas", Abbreviation = "VE-N", Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" }); states.Add('g', new State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Capital = "Valencia" }); states.Add('c', new State(name: "Apure", capital: "San Fernando de Apure", abbrv: "VE-C", area: 29500, areaSqrKms: 76500)); } @functions{ interface IGovernmentEntity { string? Name { get; set; } int Area { get; set; } string? Capital { get; set; } } interface IAbbreviated { string? Abbreviation { get; set; } } public class State : IGovernmentEntity, IAbbreviated, IComparable { public string? Name { get; set; } public int Area { get; set; } public string? Capital { get; set; } public string? Abbreviation { get; set; } public int AreaSqrKms { get; set; } public State() { Abbreviation = ""; Name = "Unknown"; Area = 0; Capital = "None"; AreaSqrKms = 0; } public State(string abbreviation) { Abbreviation = abbreviation; } public State(string? abbrv, string name, int area, int areaSqrKms, string capital) { Name = name; Area = area; Capital = capital; AreaSqrKms = areaSqrKms; abbrv = Abbreviation; } public int CompareTo(object? stt) { if (stt == null) { return 0; } State? other = stt as State; if (other != null) return Name!.CompareTo(other.Name); return 0; } public override bool Equals(object? obj) { State? stt = obj as State; if (stt!.Name == Name) return true; return false; } public override int GetHashCode() { return HashCode.Combine(Abbreviation); } } }
Objects as Keys
All the dictionary keys we have used so far were based on values of primitive types. In reality, a key can use almost any type of object. You can use a class from the .NET library or you can use your own class. Here is an example of such a class:
namespace Exercises.Models { interface IGovernmentEntity { string? Name { get; set; } int Area { get; set; } string? Capital { get; set; } } interface IAbbreviated { string? Abbreviation { get; set; } } public class Abbreviated : IAbbreviated { private string? abbrv; public string? Abbreviation { get { return abbrv; } set { abbrv = value; } } public Abbreviated(string abbrev) { abbrv = abbrev; } } public class State : IComparable, IGovernmentEntity { // From the IGovernmentEntity interface public string? Name { get; set; } public int Area { get { return AreaSqrMiles; } set { AreaSqrMiles = value; } } public string? Capital { get; set; } // New Properties public string? StateName => Name; public int AreaSqrMiles { get; set; } public int AreaSqrKms { get; set; } //public Region Region { get; set; } public string[]? SignificanCities { get; set; } public int CompareTo(object? stt) { if (stt == null) { return 0; } State? other = stt as State; if (other != null) return StateName!.CompareTo(other.StateName); return 0; } } }
You can then use the objects of the class as keys (the value can be a primitive type or an object). To specify a key, you can first declare a variable of the class and pass that variable as the first argument of the dictionary, or you can initialize the object directly in the placeholder of the dictionary variable. Here are examples:
@page @model Exercises.Pages.AustraliaModel @using Exercises.Models @{ Dictionary<Abbreviated, State> states = new Dictionary<Abbreviated, State>(); string[] WesternAustralia = new string[1] { "Perth" }; Abbreviated wa = new Abbreviated("WA"); states.Add(wa, new State() { Name = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth", SignificanCities = WesternAustralia }); Abbreviated sa = new Abbreviated("SA"); states.Add(sa, new State() { Name = "South Australia", SignificanCities = new string[] { "Adelaide" }, AreaSqrKms = 983482, Capital = "Adelaide" }); states.Add(new Abbreviated("QLD"), new State() { Name = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane", SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast", "Townsville", "Cairns", "Toowoomba" } }); states.Add(new Abbreviated("NSW"), new State() { Capital = "Sydney", Name = "New South Wales", AreaSqrKms = 800642, SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan", "Tweed Heads", "Maitland", "Wollongong", "Albury" } }); states.Add(new Abbreviated("VIC"), new State() { SignificanCities = new string[] { "Melbourne", "Geelong", "Ballarat", "Bendigo", "Wodonga" }, Name = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" }); states.Add(new Abbreviated("TAS"), new State() { Name = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart", SignificanCities = new string[] { "Hobart", "Launceston"} }); }
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
@{
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. If you try adding a key that exists already in the list, the compiler would throw an ArgumentException exception. Based on this, the following code would not work because, on the third call, a "Patrick" key exists already:
@{ System.Collections.Hashtable Students = new System.Collections.Hashtable(); Students.Add("Hermine", "Tolston"); Students.Add("Patrick", "Donley"); Students.Add("Chrissie", "Hannovers"); Students.Add("Patrick", "Herzog"); }
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
@{
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.
The key and the value can be of primitive types. In this case, write the key directly in the square brackets. Here are examples:
@using System.Collections.Generic
@{
Dictionary<int, float> baseSalaries = new()
{
[0] = 20_000f,
[1] = 32_500f,
[2] = 48_000f
};
}
The key can be of a primitive type while the value is a string. Here are examples:
@using System.Collections.Generic @{ Dictionary<int, string> typesOfProperties = new() { [1] = "Single Family", [2] = "Townhouse", [3] = "Condominium" }; }
The key can be of a character. In this case, write the key in single-quotes. The key can be of a string. In this case, type the key in double-quotes. Here are examples:
@using System.Collections.Generic @{ Dictionary<char, float> employmentSalaries = new() { ['c'] = 20_000f, ['p'] = 32_500f, ['f'] = 48_000f }; Dictionary<string, string> typesOfProperties = new() { ["SF"] = "Single Family", ["TH"] = "Townhouse", ["CO"] = "Condominium" }; }
Of course, the value can be an object of a class. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@using System.Collections
@{
Dictionary<int, string> regions = new Dictionary<int, string>();
regions.Add(1, "Capital");
regions.Add(2, "Central");
regions.Add(3, "Central-Western");
regions.Add(4, "Eastern");
regions.Add(5, "Andean");
regions.Add(6, "Zulian");
regions.Add(7, "Llanos");
regions.Add(8, "Insular");
regions.Add(9, "Guayana");
Dictionary<char, State> states = new Dictionary<char, State>();
State state = new State();
state.Abbreviation = "VE-H";
state.Name = "Cojedes";
state.Area = 5700;
state.AreaSqrKms = 14800;
state.Capital = "San Carlos";
states.Add('h', state);
state = new State();
state.Area = 25091;
state.Name = "Guárico";
state.AreaSqrKms = 64986;
state.Abbreviation = "VE-J";
state.Capital = "San Juan de Los Morros";
states.Add('j', state);
state = new State();
state.AreaSqrKms = 35200;
state.Area = 13600;
state.Abbreviation = "VE-E";
state.Name = "Barinas";
state.Capital = "Barinas";
states.Add('e', state);
state = new State() { Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" };
states.Add('m', state);
state = new State() { Capital = "Barcelona", Area = 16700, AreaSqrKms = 43300, Name = "Anzoátegui", Abbreviation = "VE-B" };
states.Add('b', state);
state = new State() { Name = "Monagas", Abbreviation = "VE-N", Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" };
states.Add('n', state);
state = new State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Capital = "Valencia" };
states.Add('g', state);
state = new State() { Name = "Apure", Capital = "San Fernando de Apure", Abbreviation = "VE-C", Area = 29500, AreaSqrKms = 76500 };
states.Add('c', state);
states.Add('y', new State() { Abbreviation = "VE-Y", Name = "Delta Amacuro", Area = 15500, AreaSqrKms = 40200, Capital = "Tucupita" });
states.Add('l', new State() { Name = "Mérida", Abbreviation = "VE-L", Area = 4400, AreaSqrKms = 11300, Capital = "Mérida" });
states.Add('f', new State() { Name = "Bolívar", Area = 240528, Abbreviation = "VE-F", AreaSqrKms = 92868, Capital = "Ciudad Bolívar" });
states.Add('i', new State() { Name = "Falcón", Area = 9600, AreaSqrKms = 24800, Abbreviation = "VE-I", Capital = "Coro" });
states.Add('z', new State() { Name = "Amazonas", Area = 70800, AreaSqrKms = 183500, Capital = "Puerto Ayacucho", Abbreviation = "VE-Z" });
states.Add('d', new State() { Abbreviation = "VE-D", Name = "Aragua", Area = 2708, AreaSqrKms = 7014, Capital = "Maracay" });
states.Add('k', new State() { Abbreviation = "VE-K", Name = "Lara", Area = 7600, AreaSqrKms = 19800, Capital = "Barquisimeto" });
states.Add('x', new State() { Abbreviation = "VE-X", Name = "Vargas", Area = 453, AreaSqrKms = 1172, Capital = "La Guaira" });
states.Add('u', new State() { Abbreviation = "VE-U", Name = "Yaracuy", Area = 2700, AreaSqrKms = 7100, Capital = "San Felipe" });
states.Add('v', new State() { Abbreviation = "VE-V", Name = "Zulia", Area = 19390, AreaSqrKms = 50230, Capital = "Maracaibo" });
states.Add('t', new State() { Abbreviation = "VE-T", Name = "Trujillo", Area = 2779, AreaSqrKms = 7198, Capital = "Trujillo" });
states.Add('p', new State() { Abbreviation = "VE-P", Name = "Portuguesa", Area = 5900, AreaSqrKms = 15200, Capital = "Guanare" });
states.Add('s', new State() { Abbreviation = "VE-S", Name = "Táchira", Area = 4175, AreaSqrKms = 10812, Capital = "San Cristóbal" });
states.Add('o', new State() { Abbreviation = "VE-O", Name = "Nueva Esparta", Area = 444, AreaSqrKms = 1151, Capital = "La Asunción" });
states.Add('r', new State() { Abbreviation = "VE-R", Name = "Sucre", Area = 4600, AreaSqrKms = 11800, Capital = "Cumaná" });
State capital = new State();
capital.Abbreviation = "VE-A";
capital.AreaSqrKms = 167;
capital.Area = 433;
capital.Capital = "Caracas";
capital.Name = "Capital District";
Dictionary<char, State> specialAreas = new Dictionary<char, State>
{
['a'] = capital,
['w'] = new State() { Abbreviation = "VE-W", Name = "Federal Dependencies", Area = 342, AreaSqrKms = 132, Capital = "Los Roques" }
};
}
@functions{
interface IGovernmentEntity
{
string? Name { get; set; }
int Area { get; set; }
string? Capital { get; set; }
}
interface IAbbreviated
{
string? Abbreviation { get; set; }
}
public class State : IGovernmentEntity, IAbbreviated, IComparable
{
public string? Name { get; set; }
public int Area { get; set; }
public string? Capital { get; set; }
public string? Abbreviation { get; set; }
public int AreaSqrKms { get; set; }
public State()
{
Abbreviation = "";
Name = "Unknown";
Area = 0;
Capital = "None";
AreaSqrKms = 0;
}
public State(string abbreviation)
{
Abbreviation = abbreviation;
}
public State(string? abbrv, string name, int area, int areaSqrKms, string capital)
{
Name = name;
Area = area;
Capital = capital;
AreaSqrKms = areaSqrKms;
abbrv = Abbreviation;
}
public int CompareTo(object? stt)
{
if (stt == null)
{
return 0;
}
State? other = stt as State;
if (other != null)
return Name!.CompareTo(other.Name);
return 0;
}
public override bool Equals(object? obj)
{
State? stt = obj as State;
if (stt!.Name == Name)
return true;
return false;
}
public override int GetHashCode()
{
return HashCode.Combine(Abbreviation);
}
}
}
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
@{
Hashtable customers = new();
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
@{
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(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 possitble 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:
@page
@model Exercises.Pages.ExerciseModel
@using System.Collections
@{
Hashtable customers = new();
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(customers);
clients.Add("G-4208-3529", "Government");
clients.Add("G-2720-2483", "Government");
clients.Add("G-7350-8074", "Government");
}
@foreach (System.Collections.DictionaryEntry entry in clients)
{
<p>@entry.Key: @entry.Value</p>
}
This would produce:
Customers Records G-7350-8074: Government G-205-628: Residential G-2720-2483: Government K-927-395: Residential H-858-337-T: Commercial L-975-275-M: Commercial G-4208-3529: Government
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:
@page @model Exercises.Pages.ExerciseModel @using System.Collections @{ Dictionary<string, string> molecules = new Dictionary<string, string>(); molecules.Add("H2O", "Water"); molecules.Add("N2", "Nitrogen"); molecules.Add("CaO", "Calcium Oxide"); molecules.Add("NaCl", "Table Salt"); molecules.Add("C6H12O6", "Glucose"); } <h2 style="font-family: 'Times New Roman'; font-weight: bold">Molecules</h2> <table class="table" style="font-family: 'Times New Roman';"> <tr> <td style="font-weight: bold">Formula</td> <td style="font-weight: bold">Common Name</td> </tr> @foreach (KeyValuePair<string, string> product in molecules) { <tr> <td>@product.Key</td> <td>@product.Value</td> </tr> } </table>
This would produce:
In the same way, you can access the members of a value that itself is an object from a class. Here are examples:
@page @model Exercises.Pages.AustraliaModel @using Exercises.Models @{ Dictionary<Abbreviated, State> states = new Dictionary<Abbreviated, State>(); string[] WesternAustralia = new string[1] { "Perth" }; Abbreviated wa = new Abbreviated("WA"); states.Add(wa, new State() { Name = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth", SignificanCities = WesternAustralia }); Abbreviated sa = new Abbreviated("SA"); states.Add(sa, new State() { Name = "South Australia", SignificanCities = new string[] { "Adelaide" }, AreaSqrKms = 983482, Capital = "Adelaide" }); states.Add(new Abbreviated("QLD"), new State() { Name = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane", SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast", "Townsville", "Cairns", "Toowoomba" } }); states.Add(new Abbreviated("NSW"), new State() { Capital = "Sydney", Name = "New South Wales", AreaSqrKms = 800642, SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan", "Tweed Heads", "Maitland", "Wollongong", "Albury" } }); states.Add(new Abbreviated("VIC"), new State() { SignificanCities = new string[] { "Melbourne", "Geelong", "Ballarat", "Bendigo", "Wodonga" }, Name = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" }); states.Add(new Abbreviated("TAS"), new State() { Name = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart", SignificanCities = new string[] { "Hobart", "Launceston"} }); } <div align="center" style="font-family: Georgia, Garamond, 'Times New Roman', Times, serif"> <h2 class="text-center">Commonwealth of Australia</h2> <table class="table"> <tr> <td class="text-center"><b>Abbreviation</b></td> <td class="text-center"><b>State Name</b></td> <td class="text-center"><b>Area</b></td> <td><b>Capital</b></td> <td><b>Significan Cities</b></td> </tr> @foreach(KeyValuePair<Abbreviated, State> juridiction in states) { <tr> <td class="text-center">@juridiction.Key.Abbreviation</td> <td>@juridiction.Value.StateName</td> <td class="text-right">@juridiction.Value.AreaSqrKms Km<sup>2</sup></td> <td>@juridiction.Value.Capital</td> <td> @for (int city = 0; city <= @juridiction.Value.SignificanCities?.Length - 1; city++) { @juridiction.Value.SignificanCities?[city]<br />; } </td> </tr> } </table> </div>
This would produce:
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:
@page
@model Exercises.Pages.ExerciseModel
@{
System.Collections.Hashtable polygons = new System.Collections.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");
}
<h2>Polygons</h2>
<p>A @polygons[5] is a polygon that has 5 edges.</p>
This would produce:
Polygons A pentagon is a polygon that has 5 edges.
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 as "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 systax for the Dictionary<> class is:
public bool ContainsKey(TKey key);
To look for an item, pass its key as argument to this method. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ Dictionary<string, string> molecules = new Dictionary<string, string>(); molecules.Add("H2O", "Water"); molecules.Add("N2", "Nitrogen"); molecules.Add("CaO", "Calcium Oxide"); molecules.Add("NaCl", "Table Salt"); molecules.Add("C6H12O6", "Glucose"); string formula = "NaCl"; bool found = molecules.ContainsKey(formula); } <h2 style="font-family: 'Times New Roman'; font-weight: bold">Molecules</h2> @if (found == true) { <p>Our list of molecules contains @formula.</p> } else { <p>Our list of molecules doesn't contain @formula.</p> } @{ formula = "DEL2W"; found = molecules.ContainsKey(formula); } @if (found == true) { <p>Our list of molecules contains @formula.</p> } else { <p>Our list of molecules doesn't contain @formula.</p> }
This would produce:
Molecules Our list of molecules contains NaCl. Our list of molecules doesn't contain DEL2W.
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:
@page @model Exercises.Pages.StatesStatisticsModel @{ Dictionary<int, string> regions = new Dictionary<int, string>(); regions.Add(1, "Capital"); regions.Add(2, "Central"); regions.Add(3, "Central-Western"); regions.Add(4, "Eastern"); regions.Add(5, "Andean"); regions.Add(6, "Zulian"); regions.Add(7, "Llanos"); regions.Add(8, "Insular"); regions.Add(9, "Guayana"); Dictionary<char, State> states = new Dictionary<char, State>(); State state = new State(); state.Abbreviation = "VE-H"; state.Name = "Cojedes"; state.Area = 5700; state.AreaSqrKms = 14800; state.Capital = "San Carlos"; states.Add('h', state); state = new State(); state.Area = 25091; state.Name = "Guárico"; state.AreaSqrKms = 64986; state.Abbreviation = "VE-J"; state.Capital = "San Juan de Los Morros"; states.Add('j', state); state = new State(); state.AreaSqrKms = 35200; state.Area = 13600; state.Abbreviation = "VE-E"; state.Name = "Barinas"; state.Capital = "Barinas"; states.Add('e', state); state = new State() { Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" }; states.Add('m', state); state = new State() { Capital = "Barcelona", Area = 16700, AreaSqrKms = 43300, Name = "Anzoátegui", Abbreviation = "VE-B" }; states.Add('b', state); state = new State() { Name = "Monagas", Abbreviation = "VE-N", Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" }; states.Add('n', state); state = new State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Capital = "Valencia" }; states.Add('g', state); state = new State() { Name = "Apure", Capital = "San Fernando de Apure", Abbreviation = "VE-C", Area = 29500, AreaSqrKms = 76500 }; states.Add('c', state); states.Add('y', new State() { Abbreviation = "VE-Y", Name = "Delta Amacuro", Area = 15500, AreaSqrKms = 40200, Capital = "Tucupita" }); states.Add('l', new State() { Name = "Mérida", Abbreviation = "VE-L", Area = 4400, AreaSqrKms = 11300, Capital = "Mérida" }); states.Add('f', new State() { Name = "Bolívar", Area = 240528, Abbreviation = "VE-F", AreaSqrKms = 92868, Capital = "Ciudad Bolívar" }); states.Add('i', new State() { Name = "Falcón", Area = 9600, AreaSqrKms = 24800, Abbreviation = "VE-I", Capital = "Coro" }); states.Add('z', new State() { Name = "Amazonas", Area = 70800, AreaSqrKms = 183500, Capital = "Puerto Ayacucho", Abbreviation = "VE-Z" }); states.Add('d', new State() { Abbreviation = "VE-D", Name = "Aragua", Area = 2708, AreaSqrKms = 7014, Capital = "Maracay" }); states.Add('k', new State() { Abbreviation = "VE-K", Name = "Lara", Area = 7600, AreaSqrKms = 19800, Capital = "Barquisimeto" }); states.Add('x', new State() { Abbreviation = "VE-X", Name = "Vargas", Area = 453, AreaSqrKms = 1172, Capital = "La Guaira" }); states.Add('u', new State() { Abbreviation = "VE-U", Name = "Yaracuy", Area = 2700, AreaSqrKms = 7100, Capital = "San Felipe" }); states.Add('v', new State() { Abbreviation = "VE-V", Name = "Zulia", Area = 19390, AreaSqrKms = 50230, Capital = "Maracaibo" }); states.Add('t', new State() { Abbreviation = "VE-T", Name = "Trujillo", Area = 2779, AreaSqrKms = 7198, Capital = "Trujillo" }); states.Add('p', new State() { Abbreviation = "VE-P", Name = "Portuguesa", Area = 5900, AreaSqrKms = 15200, Capital = "Guanare" }); states.Add('s', new State() { Abbreviation = "VE-S", Name = "Táchira", Area = 4175, AreaSqrKms = 10812, Capital = "San Cristóbal" }); states.Add('o', new State() { Abbreviation = "VE-O", Name = "Nueva Esparta", Area = 444, AreaSqrKms = 1151, Capital = "La Asunción" }); states.Add('r', new State() { Abbreviation = "VE-R", Name = "Sucre", Area = 4600, AreaSqrKms = 11800, Capital = "Cumaná" }); State capital = new State(); capital.Abbreviation = "VE-A"; capital.AreaSqrKms = 167; capital.Area = 433; capital.Capital = "Caracas"; capital.Name = "Capital District"; Dictionary<char, State> specialAreas = new Dictionary<char, State> { ['a'] = capital, ['w'] = new State() { Abbreviation = "VE-W", Name = "Federal Dependencies", Area = 342, AreaSqrKms = 132, Capital = "Los Roques" } }; State entity = new State(); entity.Name = "Trujillo"; bool found = states.ContainsValue(entity); } @functions{ interface IGovernmentEntity { string? Name { get; set; } int Area { get; set; } string? Capital { get; set; } } interface IAbbreviated { string? Abbreviation { get; set; } } public class State : IGovernmentEntity, IAbbreviated, IComparable { public string? Name { get; set; } public int Area { get; set; } public string? Capital { get; set; } public string? Abbreviation { get; set; } public int AreaSqrKms { get; set; } public State() { Abbreviation = ""; Name = "Unknown"; Area = 0; Capital = "None"; AreaSqrKms = 0; } public State(string abbreviation) { Abbreviation = abbreviation; } public State(string? abbrv, string name, int area, int areaSqrKms, string capital) { Name = name; Area = area; Capital = capital; AreaSqrKms = areaSqrKms; abbrv = Abbreviation; } public int CompareTo(object? stt) { if (stt == null) { return 0; } State? other = stt as State; if (other != null) return Name!.CompareTo(other.Name); return 0; } public override bool Equals(object? obj) { State? stt = obj as State; if (stt!.Name == Name) return true; return false; } public override int GetHashCode() { return HashCode.Combine(Abbreviation); } } } <h2 style="font-family: 'Times New Roman'; font-weight: bold">States Statistics - Venezuela</h2> @if (found == true) { <p>There exists a state named @entity.Name in Venezuela.</p> } else { <p>Venezuela doesn't have a state named @entity.Name.</p> } @{ entity.Name = "California"; found = states.ContainsValue(entity); } @if (found == true) { <p>There exists a state named @entity.Name in Venezuela.</p> } else { <p>Venezuela doesn't have a state named @entity.Name.</p> }
This would produce:
States Statistics - Venezuela There exists a state named Trujillo in Venezuela. Venezuela doesn't have a state named California.
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 are examples:
@page @model Exercises.Pages.StatesStatisticsModel @{ Dictionary<int, string> regions = new Dictionary<int, string>(); regions.Add(1, "Capital"); regions.Add(2, "Central"); regions.Add(3, "Central-Western"); regions.Add(4, "Eastern"); regions.Add(5, "Andean"); regions.Add(6, "Zulian"); regions.Add(7, "Llanos"); regions.Add(8, "Insular"); regions.Add(9, "Guayana"); Dictionary<char, State> states = new Dictionary<char, State>(); State state = new State(); state.Abbreviation = "VE-H"; state.Name = "Cojedes"; state.Area = 5700; state.AreaSqrKms = 14800; state.Capital = "San Carlos"; states.Add('h', state); state = new State(); state.Area = 25091; state.Name = "Guárico"; state.AreaSqrKms = 64986; state.Abbreviation = "VE-J"; state.Capital = "San Juan de Los Morros"; states.Add('j', state); state = new State(); state.AreaSqrKms = 35200; state.Area = 13600; state.Abbreviation = "VE-E"; state.Name = "Barinas"; state.Capital = "Barinas"; states.Add('e', state); state = new State() { Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" }; states.Add('m', state); state = new State() { Capital = "Barcelona", Area = 16700, AreaSqrKms = 43300, Name = "Anzoátegui", Abbreviation = "VE-B" }; states.Add('b', state); state = new State() { Name = "Monagas", Abbreviation = "VE-N", Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" }; states.Add('n', state); state = new State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Capital = "Valencia" }; states.Add('g', state); state = new State() { Name = "Apure", Capital = "San Fernando de Apure", Abbreviation = "VE-C", Area = 29500, AreaSqrKms = 76500 }; states.Add('c', state); states.Add('y', new State() { Abbreviation = "VE-Y", Name = "Delta Amacuro", Area = 15500, AreaSqrKms = 40200, Capital = "Tucupita" }); states.Add('l', new State() { Name = "Mérida", Abbreviation = "VE-L", Area = 4400, AreaSqrKms = 11300, Capital = "Mérida" }); states.Add('f', new State() { Name = "Bolívar", Area = 240528, Abbreviation = "VE-F", AreaSqrKms = 92868, Capital = "Ciudad Bolívar" }); states.Add('i', new State() { Name = "Falcón", Area = 9600, AreaSqrKms = 24800, Abbreviation = "VE-I", Capital = "Coro" }); states.Add('z', new State() { Name = "Amazonas", Area = 70800, AreaSqrKms = 183500, Capital = "Puerto Ayacucho", Abbreviation = "VE-Z" }); states.Add('d', new State() { Abbreviation = "VE-D", Name = "Aragua", Area = 2708, AreaSqrKms = 7014, Capital = "Maracay" }); states.Add('k', new State() { Abbreviation = "VE-K", Name = "Lara", Area = 7600, AreaSqrKms = 19800, Capital = "Barquisimeto" }); states.Add('x', new State() { Abbreviation = "VE-X", Name = "Vargas", Area = 453, AreaSqrKms = 1172, Capital = "La Guaira" }); states.Add('u', new State() { Abbreviation = "VE-U", Name = "Yaracuy", Area = 2700, AreaSqrKms = 7100, Capital = "San Felipe" }); states.Add('v', new State() { Abbreviation = "VE-V", Name = "Zulia", Area = 19390, AreaSqrKms = 50230, Capital = "Maracaibo" }); states.Add('t', new State() { Abbreviation = "VE-T", Name = "Trujillo", Area = 2779, AreaSqrKms = 7198, Capital = "Trujillo" }); states.Add('p', new State() { Abbreviation = "VE-P", Name = "Portuguesa", Area = 5900, AreaSqrKms = 15200, Capital = "Guanare" }); states.Add('s', new State() { Abbreviation = "VE-S", Name = "Táchira", Area = 4175, AreaSqrKms = 10812, Capital = "San Cristóbal" }); states.Add('o', new State() { Abbreviation = "VE-O", Name = "Nueva Esparta", Area = 444, AreaSqrKms = 1151, Capital = "La Asunción" }); states.Add('r', new State() { Abbreviation = "VE-R", Name = "Sucre", Area = 4600, AreaSqrKms = 11800, Capital = "Cumaná" }); State capital = new State(); capital.Abbreviation = "VE-A"; capital.AreaSqrKms = 167; capital.Area = 433; capital.Capital = "Caracas"; capital.Name = "Capital District"; Dictionary<char, State> specialAreas = new Dictionary<char, State> { ['a'] = capital, ['w'] = new State() { Abbreviation = "VE-W", Name = "Federal Dependencies", Area = 342, AreaSqrKms = 132, Capital = "Los Roques" } }; } @functions{ interface IGovernmentEntity { string? Name { get; set; } int Area { get; set; } string? Capital { get; set; } } interface IAbbreviated { string? Abbreviation { get; set; } } public class State : IGovernmentEntity, IAbbreviated, IComparable { public string? Name { get; set; } public int Area { get; set; } public string? Capital { get; set; } public string? Abbreviation { get; set; } public int AreaSqrKms { get; set; } public State() { Abbreviation = ""; Name = "Unknown"; Area = 0; Capital = "None"; AreaSqrKms = 0; } public State(string abbreviation) { Abbreviation = abbreviation; } public State(string? abbrv, string name, int area, int areaSqrKms, string capital) { Name = name; Area = area; Capital = capital; AreaSqrKms = areaSqrKms; abbrv = Abbreviation; } public int CompareTo(object? stt) { if (stt == null) { return 0; } State? other = stt as State; if (other != null) return Name!.CompareTo(other.Name); return 0; } public override bool Equals(object? obj) { State? stt = obj as State; if (stt!.Name == Name) return true; return false; } public override int GetHashCode() { return HashCode.Combine(Abbreviation); } } } <h2 style="font-family: 'Times New Roman'; font-weight: bold">States Statistics - Venezuela</h2> @{ char letter = 'o'; State? entity = new State(); bool found = states.TryGetValue(letter, out entity); } @if (found == true) { <p>Abbreviation: VE-@letter.ToString().ToUpper()</p> <p>State Name: @entity!.Name</p> } else { throw new System.NullReferenceException("There is no state with that abbreviation in the collection."); }
This would produce:
States Statistics - Venezuela Abbreviation: VE-O State Name: Nueva Esparta
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 dlete. Here is an example:
@page @model Exercises.Pages.ExerciseModel @{ Dictionary<string, string> molecules = new Dictionary<string, string>(); molecules.Add("H2O", "Water"); molecules.Add("N2", "Nitrogen"); molecules.Add("CaO", "Calcium Oxide"); molecules.Add("NaCl", "Table Salt"); molecules.Add("C6H12O6", "Glucose"); } <h2 style="font-family: 'Times New Roman'; font-weight: bold">Molecules</h2> <hr /> <table class="table" style="font-family: 'Times New Roman';"> <tr> <td style="font-weight: bold">Formula</td> <td style="font-weight: bold">Common Name</td> </tr> @foreach (KeyValuePair<string, string> product in molecules) { <tr> <td>@product.Key</td> <td>@product.Value</td> </tr> } </table> @{ molecules.Remove("N2"); } <h2 style="font-family: 'Times New Roman'; font-weight: bold">Molecules</h2> <hr /> <table class="table" style="font-family: 'Times New Roman';"> <tr> <td style="font-weight: bold">Formula</td> <td style="font-weight: bold">Common Name</td> </tr> @foreach (KeyValuePair<string, string> product in molecules) { <tr> <td>@product.Key</td> <td>@product.Value</td> </tr> } </table>
This would produce:
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 namedd 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 distionary-based classes also support this concept.
Instead of making you create a dictionary class that supports ordering the items, the .NET library provides 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.
When using a sorted-dictionary class, the key must support ordering. If you are using a primitive type for the keys, all their structures can handle ordering. If you are using objects for keys, the class of those keys must implement the IComparable interface. In that interface, you must let the compiler know how the objects of that class would be compared to know which one comes after which. Here is example of a class that implements the IComparable interface:
namespace Exercises.Models { interface IGovernmentEntity { string? Name { get; set; } int Area { get; set; } string? Capital { get; set; } } interface IAbbreviated { string? Abbreviation { get; set; } } public class Abbreviated : IComparable, IAbbreviated { private string? abbrv; public string? Abbreviation { get { return abbrv; } set { abbrv = value; } } public Abbreviated(string abbrev) { abbrv = abbrev; } public int CompareTo(object? stt) { if (stt == null) { return 0; } Abbreviated? other = stt as Abbreviated; if (other != null) return Abbreviation!.CompareTo(other.Abbreviation); return 0; } } public class State : IGovernmentEntity { // From the IGovernmentEntity interface public string? Name { get; set; } public int Area { get { return AreaSqrMiles; } set { AreaSqrMiles = value; } } public string? Capital { get; set; } // New Properties public string? StateName => Name; public int AreaSqrMiles { get; set; } public int AreaSqrKms { get; set; } //public Region Region { get; set; } public string[]? SignificanCities { get; set; } } }
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.
Accessing the Items of a Sorted Dictionary
The Items of a sorted dictionary are accessed with the same techniques we used for the regular dictionary classes. Here are examples:
@page @model Exercises.Pages.AustraliaModel @using Exercises.Models @{ SortedDictionary<Abbreviated, State> states = new SortedDictionary<Abbreviated, State>(); string[] WesternAustralia = new string[1] { "Perth" }; Abbreviated wa = new Abbreviated("WA"); states.Add(wa, new State() { Name = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth", SignificanCities = WesternAustralia }); Abbreviated sa = new Abbreviated("SA"); states.Add(sa, new State() { Name = "South Australia", SignificanCities = new string[] { "Adelaide" }, AreaSqrKms = 983482, Capital = "Adelaide" }); states.Add(new Abbreviated("QLD"), new State() { Name = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane", SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast", "Townsville", "Cairns", "Toowoomba" } }); states.Add(new Abbreviated("NSW"), new State() { Capital = "Sydney", Name = "New South Wales", AreaSqrKms = 800642, SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan", "Tweed Heads", "Maitland", "Wollongong", "Albury" } }); states.Add(new Abbreviated("VIC"), new State() { SignificanCities = new string[] { "Melbourne", "Geelong", "Ballarat", "Bendigo", "Wodonga" }, Name = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" }); states.Add(new Abbreviated("TAS"), new State() { Name = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart", SignificanCities = new string[] { "Hobart", "Launceston"} }); } <div align="center" style="font-family: Georgia, Garamond, 'Times New Roman', Times, serif"> <h2 class="text-center">Commonwealth of Australia</h2> <table class="table"> <tr> <td class="text-center"><b>Abbreviation</b></td> <td class="text-center"><b>State Name</b></td> <td class="text-center"><b>Area</b></td> <td><b>Capital</b></td> <td><b>Significan Cities</b></td> </tr> @foreach(KeyValuePair<Abbreviated, State> juridiction in states) { <tr> <td class="text-center">@juridiction.Key.Abbreviation</td> <td>@juridiction.Value.StateName</td> <td class="text-right">@juridiction.Value.AreaSqrKms Km<sup>2</sup></td> <td>@juridiction.Value.Capital</td> <td> @for (int city = 0; city <= @juridiction.Value.SignificanCities?.Length - 1; city++) { @juridiction.Value.SignificanCities?[city]<br />; } </td> </tr> } </table> </div>
This would produce:
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-2022, FunctionX | Thursday 10 March 2022 | Next |
|