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.
Practical Learning: Introducing Dictionary Collections
body { background-image: url('../Images/background1.png'); } .navbar-inverse { background-color: #5C0700; border-bottom: 6px solid black; } .navbar-fixed-bottom { height: 60px; background-color: #5C0700; border-top: 6px solid black; } .col-md-3 { min-height: 350px; background-color: transparent; } .col-md-4 { width: 30%; } .col-md-9 { padding-left: 80px; } .row { margin-right: 0; margin-left: 0; } .jumbotron { margin-bottom: 3px; padding: 10px; background-color: #FFCC80; background-image: url('../Images/globe2.png'); } .jumbotron h1 { color: antiquewhite } .lead { color: lightgoldenrodyellow } .navbar-inverse .navbar-nav > li > a { color: #999999; } .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { color: #ffffff; background: linear-gradient(#5C0700, #af8673, #5C0700); } .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { color: #ffffff; background-color: #080808; } .left-menu-group { list-style-type: none; } .left-menu-title { font-weight: 600; width: 100%; padding-left: 20px; margin-left: -10px; height: 1.62em; font-size: 1.55em; color: lightyellow; border-bottom: 2px solid yellow; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .left-menu-group li { height: 1.62em; font-size: 1.35em; margin-left: -45px; padding-left: 20px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .left-menu-group li:hover { font-size: 1.35em; border: 1px dashed maroon; background-color: antiquewhite; } .centralizer { margin: auto; width: 710px; } .tblStates { margin: auto; width: 320px; } .tblStates table { width: 100%; } .colorized { color: antiquewhite; } .country-title { font-size: 30px; font-weight: 500; line-height: 1.1; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; } .tbl-header { width: 120px; border-bottom: 2px solid black; }
namespace CountriesStatistics2.Models { interface IGovernmentEntity { string Name { get; set; } int Area { get; set; } string Capital { get; set; } } }
namespace CountriesStatistics2.Models { interface IAbbreviated { string Abbreviation { get; set; } } }
using System; namespace CountriesStatistics2.Models { public class State : IGovernmentEntity, IAbbreviated, IComparable { // From the IAbbreviated interface public string Abbreviation { get; set; } // From the IGovernmentEntity interface public string Name { get; set; } public int Area { get; set; } public string Capital { get; set; } // New Properties public string StateName => Name; public int AreaSqrMiles => Area; public int AreaSqrKms { get; set; } // New Members public State() { Abbreviation = ""; Name = "Unknown"; Area = 0; Capital = "None"; AreaSqrKms = 0; } 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 State(string abbrv, string name, int area, int areaSqrKms, string capital) { Name = name; Area = area; Capital = capital; AreaSqrKms = areaSqrKms; abbrv = Abbreviation; } public override bool Equals(object obj) { State stt = (State)obj; if (stt.Name == Name) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class AustraliaController : Controller { // GET: Australia public ActionResult Index() { return View(); } // GET: Australia/States public ActionResult States() { return View(); } // GET: Australia/Territories public ActionResult Territories() { return View(); } } }
using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class CanadaController : Controller { // GET: Canada public ActionResult Index() { return View(); } // GET: Canada/Provinces public ActionResult Provinces() { return View(); } // GET: Canada/Territories public ActionResult Territories() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class UnitedStatesController : Controller { // GET: UnitedStates public ActionResult Index() { return View(); } // GET: UnitedStates/StatesList public ActionResult StatesList() { return View(); } // GET: UnitedStates/StateSearch public ActionResult StateSearch() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class VenezuelaController : Controller { // GET: Venezuela public ActionResult Index() { return View(); } // GET: Venezuela/StatesList public ActionResult StatesList() { return View(); } // GET: Venezuela/StateSearch public ActionResult StateSearch() { return View(); } } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CountriesStatistics2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Continents()
{
return View();
}
public ActionResult Oceans()
{
return View();
}
public ActionResult Flags()
{
return View();
}
public ActionResult Maps()
{
return View();
}
public ActionResult Historical()
{
return View();
}
}
}
@{ ViewBag.Title = "Welcome"; ViewBag.MainTitle = "Introduction"; } <div class="jumbotron"> <div class="row"> <div class="col-md-2" style="width: 120px; height: 220px"></div> <div class="col-md-9"> <h1>Countries Statistics</h1> <p class="lead"> This is a collection of resources that will assist you in studying some of the resources that various countries of this world offer, for both academic and entertainment purposes. </p> </div> </div> </div> <hr /> <div class="row"> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <img src="~/Images/australia.png" /> </div> <div class="col-md-8"> <p class="country-title">Australia</p> </div> </div> <div class="row"> <p>This section reviews the states and territories of Australia, including some information about the government and the economy.</p> <p>@Html.ActionLink("« Learn More »", "Index", "Australia", null, new { @class = "btn btn-warning" })</p> </div> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <img src="~/Images/brazil.png" /> </div> <div class="col-md-8"> <p class="country-title">Brazil</p> </div> </div> <div class="row"> <p>These are some statistics and more information about the largest and the most populous country in South America.</p> <p>@Html.ActionLink("« Learn More »", "Index", "Brazil", null, new { @class = "btn btn-warning" })</p> </div> </div> <div class="col-md-4"> <div class="row"> <div class="col-md-4"> <img src="~/Images/canada.png" /> </div> <div class="col-md-8"> <p class="country-title">Canada</p> </div> </div> <div class="row"> <p>This is one of the countries that share the world's longest border with another, its southern neighbor. Get to know Canada.</p> <p>@Html.ActionLink("« Learn More »", "Index", "Canada", null, new { @class = "btn btn-warning" })</p> </div> </div> </div> <hr /> <div class="row"> <div class="col-md-3"> <div class="row"> <div class="col-md-4"> <img src="~/Images/germany.png" /> </div> <div class="col-md-8"> <p class="country-title">Germany</p> </div> </div> <div class="row"> <p>The history, sport, geography, and politics of Germany are described in this section of our website.</p> <p>@Html.ActionLink("« Learn More »", "Index", "Germany", null, new { @class = "btn btn-warning" })</p> </div> </div> <div class="col-md-3"> <div class="row"> <div class="col-md-4"> <img src="~/Images/mexico.png" /> </div> <div class="col-md-8"> <p class="country-title">Mexico</p> </div> </div> <div class="row"> <p>Details about the Mexican states are presented, along with the tourism, culture, and entertainment.</p> <p>@Html.ActionLink("« Learn More »", "Index", "Mexico", null, new { @class = "btn btn-warning" })</p> </div> </div> <div class="col-md-3"> <div class="row"> <div class="col-md-4"> <img src="~/Images/us.png" /> </div> <div class="col-md-8"> <p class="country-title">USA</p> </div> </div> <div class="row"> <p>Review the states, territories, and other possessions of the United States, including landmarks, lakes, parks, etc.</p> <p>@Html.ActionLink("« Learn More »".ToString(), "Index", "UnitedStates", null, new { @class = "btn btn-warning" })</p> </div> </div> <div class="col-md-3"> <div class="row"> <div class="col-md-4"> <img src="~/Images/Venezuela.png" /> </div> <div class="col-md-8"> <p class="country-title">Venezuela</p> </div> </div> <div class="row"> <p>This library can help you get acquainted with Venezuela, its federal district and federal dependencies.</p> <p>@Html.ActionLink("« Learn More »".ToString(), "Index", "Venezuela", null, new { @class = "btn btn-warning" })</p> </div> </div> </div>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Countries Statistics :: @ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/CountriesStatistics.css" /> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Countries Statistics", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("The World", "Index", "Home")</li> <li>@Html.ActionLink("Oceans", "Oceans", "Home")</li> <li>@Html.ActionLink("Continents", "Continents", "Home")</li> <li>@Html.ActionLink("Flags", "Flags", "Home")</li> <li>@Html.ActionLink("Maps", "Maps", "Home")</li> <li>@Html.ActionLink("Historical Figures", "Historical", "Home")</li> <li>@Html.ActionLink("About Us", "About", "Home")</li> <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() </div> <footer class="navbar-fixed-bottom"> <h4 class="text-center colorized">© @DateTime.Now.Year - Countries Statistics</h4> </footer> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
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 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(); } }
If you are writing your code in a webpage, you must qualify the class. Here is an example:
<<!DOCTYPE html>
<html>
<head>
<title>Political Science</title>
</head>
<body>
<h2>Political Science</h2>
@{
System.Collections.Hashtable fields = new System.Collections.Hashtable();
}
</body>
</html>
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:
<!DOCTYPE html> <html> <head> <title>Customers Records</title> </head> <body> <h2>Customers Records</h2> @{ System.Collections.Generic.Dictionary<string, string> customers = new System.Collections.Generic.Dictionary<string, string>(); } </body> </html>
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:
<!DOCTYPE html>
<html>
<head>
<title>Human Resources - Personnel Analysis</title>
</head>
<body>
<h2>Human Resources - Personnel Analysis</h2>
<table>
<tr>
<td><b>Employee #</b></td><td><b>Is Full-Time</b></td>
</tr>
<tr>
<td>482508</td><td>True</td>
</tr>
<tr>
<td>935296</td><td>True</td>
</tr>
<tr>
<td>251179</td><td>False</td>
</tr>
</table>
@{
System.Collections.Hashtable employees = new System.Collections.Hashtable();
employees.Add(482508, true);
employees.Add(935296, true);
employees.Add(251179, false);
}
</body>
</html>
Remember that if you are using a generic dictionary, you must specify the parameter types. Here is an example:
<!DOCTYPE html> <html> <head> <title>Human Resources - Personnel Analysis</title> </head> <body> <h2>Human Resources - Personnel Analysis</h2> @{ System.Collections.Generic.Dictionary<int, bool> employees = new System.Collections.Generic.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:
<!DOCTYPE html>
<html>
<head>
<title>Polygons</title>
</head>
<body>
<h2>Polygons</h2>
@{
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");
}
</body>
</html>
Practical Learning: Using Value Types as Keys
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CountriesStatistics2.Controllers
{
public class VenezuelaController : Controller
{
public Dictionary<int, string> Regions;
public VenezuelaController()
{
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");
}
// GET: Venezuela
public ActionResult Index()
{
return View();
}
// GET: Venezuela/StatesList
public ActionResult StatesList()
{
return View();
}
// GET: Venezuela/StateSearch
public ActionResult StateSearch()
{
return View();
}
}
}
Strings as Keys and Values
Both the key and the value can be strings. Here are examples:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
<table>
<tr>
<td><b>Account #</b></td><td><b>Category</b></td>
</tr>
<tr>
<td>G-205-628</td><td>Residential</td>
</tr>
<tr>
<td>H-858-337-T</td><td>Commercial</td>
</tr>
<tr>
<td>L-975-275-M</td><td>Commercial</td>
</tr>
<tr>
<td>K-927-395</td><td>Residential</td>
</tr>
</table>
@{
System.Collections.Hashtable customers = new System.Collections.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");
}
</body>
</html>
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
Practical Learning: Adding Objects as Values
using System; namespace CountriesStatistics2.Controllers { public class VenezuelaController : Controller { public Dictionary<int, string> Regions; public Dictionary<char, Models.State> States; public VenezuelaController() { 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"); States = new Dictionary<char, Models.State>(); Models.State state = new Models.State(); state.Abbreviation = "VE-H"; state.Name = "Cojedes"; state.Area = 5700; state.AreaSqrKms = 14800; state.Capital = "San Carlos"; States.Add('h', state); state = new Models.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 Models.State(); state.AreaSqrKms = 35200; state.Area = 13600; state.Abbreviation = "VE-E"; state.Name = "Barinas"; state.Capital = "Barinas"; States.Add('e', state); state = new Models.State() { Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" }; States.Add('m', state); state = new Models.State() { Capital = "Barcelona", Area = 16700, AreaSqrKms = 43300, Name = "Anzoátegui", Abbreviation = "VE-B" }; States.Add('b', state); state = new Models.State() { Name = "Monagas", Abbreviation = "VE-N", Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" }; States.Add('n', state); state = new Models.State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Capital = "Valencia" }; States.Add('g', state); state = new Models.State() { Name = "Apure", Capital = "San Fernando de Apure", Abbreviation = "VE-C", Area = 29500, AreaSqrKms = 76500 }; States.Add('c', state); States.Add('y', new Models.State() { Abbreviation = "VE-Y", Name = "Delta Amacuro", Area = 15500, AreaSqrKms = 40200, Capital = "Tucupita" }); States.Add('l', new Models.State() { Name = "Mérida", Abbreviation = "VE-L", Area = 4400, AreaSqrKms = 11300, Capital = "Mérida" }); States.Add('f', new Models.State() { Name = "Bolívar", Area = 240528, Abbreviation = "VE-F", AreaSqrKms = 92868, Capital = "Ciudad Bolívar" }); States.Add('i', new Models.State() { Name = "Falcón", Area = 9600, AreaSqrKms = 24800, Abbreviation = "VE-I", Capital = "Coro" }); States.Add('z', new Models.State() { Name = "Amazonas", Area = 70800, AreaSqrKms = 183500, Capital = "Puerto Ayacucho", Abbreviation = "VE-Z" }); States.Add('d', new Models.State() { Abbreviation = "VE-D", Name = "Aragua", Area = 2708, AreaSqrKms = 7014, Capital = "Maracay" }); States.Add('k', new Models.State() { Abbreviation = "VE-K", Name = "Lara", Area = 7600, AreaSqrKms = 19800, Capital = "Barquisimeto" }); States.Add('x', new Models.State() { Abbreviation = "VE-X", Name = "Vargas", Area = 453, AreaSqrKms = 1172, Capital = "La Guaira" }); States.Add('u', new Models.State() { Abbreviation = "VE-U", Name = "Yaracuy", Area = 2700, AreaSqrKms = 7100, Capital = "San Felipe" }); States.Add('v', new Models.State() { Abbreviation = "VE-V", Name = "Zulia", Area = 19390, AreaSqrKms = 50230, Capital = "Maracaibo" }); States.Add('t', new Models.State() { Abbreviation = "VE-T", Name = "Trujillo", Area = 2779, AreaSqrKms = 7198, Capital = "Trujillo" }); States.Add('p', new Models.State() { Abbreviation = "VE-P", Name = "Portuguesa", Area = 5900, AreaSqrKms = 15200, Capital = "Guanare" }); States.Add('s', new Models.State() { Abbreviation = "VE-S", Name = "Táchira", Area = 4175, AreaSqrKms = 10812, Capital = "San Cristóbal" }); States.Add('o', new Models.State() { Abbreviation = "VE-O", Name = "Nueva Esparta", Area = 444, AreaSqrKms = 1151, Capital = "La Asunción" }); States.Add('r', new Models.State() { Abbreviation = "VE-R", Name = "Sucre", Area = 4600, AreaSqrKms = 11800, Capital = "Cumaná" }); } // GET: Venezuela public ActionResult Index() { return View(); } // GET: Venezuela/StatesList public ActionResult StatesList() { return View(); } // GET: Venezuela/StateSearch public ActionResult StateSearch() { return View(); } } }
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. 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:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
<table>
<tr>
<td><b>Account #</b></td><td><b>Category</b></td>
</tr>
<tr>
<td>G-205-628</td><td>Residential</td>
</tr>
<tr>
<td>H-858-337-T</td><td>Commercial</td>
</tr>
<tr>
<td>L-975-275-M</td><td>Commercial</td>
</tr>
<tr>
<td>K-927-395</td><td>Residential</td>
</tr>
</table>
@{
System.Collections.Hashtable customers = new System.Collections.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";
}
</body>
</html>
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.
Practical Learning: Adding Values by their Keyed Indexes
uusing System; namespace CountriesStatistics2.Controllers { public class VenezuelaController : Controller { public Dictionary<int, string> Regions; public Dictionary<char, Models.State> States; public Dictionary<char, Models.State> SpecialAreas; public VenezuelaController() { Regions = new Dictionary<int, string>(); . . . No Change Models.State capital = new Models.State(); capital.Abbreviation = "VE-A"; capital.AreaSqrKms = 167; capital.Area = 433; capital.Capital = "Caracas"; capital.Name = "Capital District"; SpecialAreas = new Dictionary<char, Models.State> { ['a'] = capital, ['w'] = new Models.State() { Abbreviation = "VE-W", Name = "Federal Dependencies", Area = 342, AreaSqrKms = 132, Capital = "Los Roques" } }; } // GET: Venezuela public ActionResult Index() { return View(); } // GET: Venezuela/StatesList public ActionResult StatesList() { return View(); } // GET: Venezuela/StateSearch public ActionResult StateSearch() { return View(); } } }
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:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
@{
System.Collections.Hashtable customers = new System.Collections.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";
System.Collections.Hashtable clients = new System.Collections.Hashtable(customers);
}
</body>
</html>
Of course, after initializing such a collection, you can add new items to it. Here are examples:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
@{
System.Collections.Hashtable customers = new System.Collections.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";
System.Collections.Hashtable clients = new System.Collections.Hashtable(customers);
clients.Add("G-4208-3529", "Government");
clients.Add("G-2720-2483", "Government");
clients.Add("G-7350-8074", "Government");
}
</body>
</html>
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:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
@{
System.Collections.Hashtable customers = new System.Collections.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";
System.Collections.Hashtable clients = new System.Collections.Hashtable(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>
}
</body>
</html>
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.
Practical Learning: Enumerating the Items of a Dictionary
@{ ViewBag.Title = "Venezuela: States and Special Entities"; } @{ int i = 1, j = 1; CountriesStatistics2.Controllers.VenezuelaController vc = new CountriesStatistics2.Controllers.VenezuelaController(); System.Collections.Generic.Dictionary<int, string> regions = vc.Regions; System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> states = vc.States; System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> specials = vc.SpecialAreas; } <div style="width: 700px; margin: auto"> <h2 class="text-center">Venezuela: States and Entities</h2> <h2 class="text-center">States</h2> <table style="width: 100%" border="3"> <tr> <td> </td> <td> </td> <td> </td> <td class="text-center" colspan="2"><b>Area</b></td> <td> </td> </tr> <tr> <td class="text-center"><b>#</b></td> <td class="text-center"><b>Abbrv</b></td> <td><b>State</b></td> <td><b>Sqr Miles</b></td> <td><b>Sqr Kms</b></td> <td><b>Capital</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<char, CountriesStatistics2.Models.State> state in states) { <tr> <td class="text-center"><b>@i</b></td> <td class="text-center">@state.Value.Abbreviation</td> <td>@state.Value.StateName</td> <td class="text-right">@state.Value.AreaSqrMiles</td> <td class="text-right">@state.Value.AreaSqrKms</td> <td>@state.Value.Capital</td> </tr> i++; } </table> <h2 class="text-center">Special Areas</h2> <table style="width: 100%" border="3"> <tr> <td> </td> <td> </td> <td> </td> <td class="text-center" colspan="2"><b>Area</b></td> <td> </td> </tr> <tr> <td class="text-center"><b>#</b></td> <td class="text-center"><b>Abbrv</b></td> <td><b>State</b></td> <td><b>Sqr Miles</b></td> <td><b>Sqr Kms</b></td> <td><b>Capital</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<char, CountriesStatistics2.Models.State> special in specials) { <tr> <td class="text-center"><b>@j</b></td> <td class="text-center">@special.Value.Abbreviation</td> <td>@special.Value.StateName</td> <td class="text-right">@special.Value.AreaSqrMiles</td> <td class="text-right">@special.Value.AreaSqrKms</td> <td>@special.Value.Capital</td> </tr> j++; } </table> </div> <div style="width: 300px; margin: auto; margin-bottom: 4em"> <h2 class="text-center">Regions</h2> <table style="width: 100%" border="3"> <tr> <td class="text-center"><b>#</b></td> <td><b>Region</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<int, string> region in regions) { <tr> <td>@region.Key</td> <td>@region.Value</td> </tr> } </table> </div>
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:
<!DOCTYPE html>
<html>
<head>
<title>Polygons</title>
</head>
<body>
<h2>Polygons</h2>
@{
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");
}
<p>A @polygons[5] is a polygon that has 5 edges.</p>
</body>
</html>
This would produce:
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. ".
Practical Learning: Getting the Value of an Item
namespace CountriesStatistics2.Models { public class State : IGovernmentEntity, IAbbreviated { // From the IAbbreviated interface public string Abbreviation { get; set; } // From the IGovernmentEntity interface public string Name { get; set; } public int Area { get; set; } public string Capital { get; set; } // New Properties public string StateName => Name; public int AreaSqrMiles => Area; public int AreaSqrKms { get; set; } public string Region { get; set; } // New Members public State() { Abbreviation = ""; Name = "Unknown"; Area = 0; Capital = "None"; AreaSqrKms = 0; Region = "Unknown"; } public State(string abbrv, string name, int area, int areaSqrKms, string capital, string region) { Name = name; Area = area; Capital = capital; Region = region; AreaSqrKms = areaSqrKms; abbrv = Abbreviation; } public override bool Equals(object obj) { State stt = (State)obj; if (stt.Name == Name) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class VenezuelaController : Controller { public Dictionary<int, string> Regions; public Dictionary<char, Models.State> States; public Dictionary<char, Models.State> SpecialAreas; public VenezuelaController() { 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"); States = new Dictionary<char, Models.State>(); Models.State state = new Models.State(); state.Abbreviation = "VE-H"; state.Name = "Cojedes"; state.Area = 5700; state.AreaSqrKms = 14800; state.Capital = "San Carlos"; state.Region = Regions[2]; States.Add('h', state); state = new Models.State(); state.Area = 25091; state.Name = "Guárico"; state.AreaSqrKms = 64986; state.Region = Regions[7]; state.Abbreviation = "VE-J"; state.Capital = "San Juan de Los Morros"; States.Add('j', state); state = new Models.State(); state.AreaSqrKms = 35200; state.Area = 13600; state.Abbreviation = "VE-E"; state.Name = "Barinas"; state.Capital = "Barinas"; state.Region = Regions[5]; States.Add('e', state); state = new Models.State() { Region = Regions[1], Abbreviation = "VE-M", Name = "Miranda", Area = 3070, AreaSqrKms = 7950, Capital = "Los Teques" }; States.Add('m', state); state = new Models.State() { Capital = "Barcelona", Region = Regions[4], Area = 16700, AreaSqrKms = 43300, Name = "Anzoátegui", Abbreviation = "VE-B" }; States.Add('b', state); state = new Models.State() { Name = "Monagas", Abbreviation = "VE-N", Region = Regions[4], Area = 11200, AreaSqrKms = 28900, Capital = "Maturín" }; States.Add('n', state); state = new Models.State() { Area = 1687, AreaSqrKms = 4369, Abbreviation = "VE-G", Name = "Carabobo", Region = Regions[2], Capital = "Valencia" }; States.Add('g', state); state = new Models.State() { Name = "Apure", Capital = "San Fernando de Apure", Abbreviation = "VE-C", Area = 29500, AreaSqrKms = 76500, Region = Regions[7] }; States.Add('c', state); States.Add('y', new Models.State() { Abbreviation = "VE-Y", Region = Regions[9], Name = "Delta Amacuro", Area = 15500, AreaSqrKms = 40200, Capital = "Tucupita" }); States.Add('l', new Models.State() { Name = "Mérida", Abbreviation = "VE-L", Area = 4400, AreaSqrKms = 11300, Region = Regions[5], Capital = "Mérida" }); States.Add('f', new Models.State() { Name = "Bolívar", Area = 240528, Region = Regions[9], Abbreviation = "VE-F", AreaSqrKms = 92868, Capital = "Ciudad Bolívar" }); States.Add('i', new Models.State() { Name = "Falcón", Region = Regions[3], Area = 9600, AreaSqrKms = 24800, Abbreviation = "VE-I", Capital = "Coro" }); States.Add('z', new Models.State() { Name = "Amazonas", Area = 70800, AreaSqrKms = 183500, Region = Regions[9], Capital = "Puerto Ayacucho", Abbreviation = "VE-Z" }); States.Add('d', new Models.State() { Abbreviation = "VE-D", Name = "Aragua", Area = 2708, AreaSqrKms = 7014, Capital = "Maracay", Region = Regions[2] }); States.Add('k', new Models.State() { Abbreviation = "VE-K", Name = "Lara", Area = 7600, AreaSqrKms = 19800, Capital = "Barquisimeto", Region = Regions[3] }); States.Add('x', new Models.State() { Abbreviation = "VE-X", Name = "Vargas", Area = 453, AreaSqrKms = 1172, Capital = "La Guaira", Region = Regions[1] }); States.Add('u', new Models.State() { Abbreviation = "VE-U", Name = "Yaracuy", Area = 2700, AreaSqrKms = 7100, Capital = "San Felipe", Region = Regions[3] }); States.Add('v', new Models.State() { Abbreviation = "VE-V", Name = "Zulia", Area = 19390, AreaSqrKms = 50230, Capital = "Maracaibo", Region = Regions[6] }); States.Add('t', new Models.State() { Abbreviation = "VE-T", Name = "Trujillo", Area = 2779, AreaSqrKms = 7198, Capital = "Trujillo", Region = Regions[5] }); States.Add('p', new Models.State() { Abbreviation = "VE-P", Name = "Portuguesa", Area = 5900, AreaSqrKms = 15200, Capital = "Guanare", Region = Regions[3] }); States.Add('s', new Models.State() { Abbreviation = "VE-S", Name = "Táchira", Area = 4175, AreaSqrKms = 10812, Capital = "San Cristóbal", Region = Regions[5] }); States.Add('o', new Models.State() { Abbreviation = "VE-O", Name = "Nueva Esparta", Area = 444, AreaSqrKms = 1151, Capital = "La Asunción", Region = Regions[8] }); States.Add('r', new Models.State() { Abbreviation = "VE-R", Name = "Sucre", Area = 4600, AreaSqrKms = 11800, Capital = "Cumaná", Region = Regions[4] }); Models.State capital = new Models.State(); capital.Abbreviation = "VE-A"; capital.AreaSqrKms = 167; capital.Area = 433; capital.Capital = "Caracas"; capital.Name = "Capital District"; capital.Region = Regions[1]; SpecialAreas = new Dictionary<char, Models.State> { ['a'] = capital, ['w'] = new Models.State() { Abbreviation = "VE-W", Name = "Federal Dependencies", Area = 342, AreaSqrKms = 132, Capital = "Los Roques", Region = Regions[8] } }; } // GET: Venezuela public ActionResult Index() { return View(); } // GET: Venezuela/StatesList public ActionResult StatesList() { return View(); } // GET: Venezuela/StateSearch public ActionResult StateSearch() { return View(); } } }
@{ ViewBag.Title = "Venezuela: States and Special Entities"; } @{ int i = 1, j = 1; CountriesStatistics2.Controllers.VenezuelaController vc = new CountriesStatistics2.Controllers.VenezuelaController(); System.Collections.Generic.Dictionary<int, string> regions = vc.Regions; System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> states = vc.States; System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> specials = vc.SpecialAreas; } <div style="width: 700px; margin: auto"> <h2 class="text-center">Venezuela: States and Entities</h2> <h2 class="text-center">States</h2> <table style="width: 100%" border="3"> <tr> <td> </td> <td> </td> <td> </td> <td class="text-center" colspan="2"><b>Area</b></td> <td> </td> <td> </td> </tr> <tr> <td class="text-center"><b>#</b></td> <td class="text-center"><b>Abbrv</b></td> <td><b>State</b></td> <td><b>Sqr Miles</b></td> <td><b>Sqr Kms</b></td> <td><b>Capital</b></td> <td><b>Region</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<char, CountriesStatistics2.Models.State> state in states) { <tr> <td class="text-center"><b>@i</b></td> <td class="text-center">@state.Value.Abbreviation</td> <td>@state.Value.StateName</td> <td class="text-right">@state.Value.AreaSqrMiles</td> <td class="text-right">@state.Value.AreaSqrKms</td> <td>@state.Value.Capital</td> <td>@state.Value.Region</td> </tr> i++; } </table> <h2 class="text-center">Special Areas</h2> <table style="width: 100%" border="3"> <tr> <td> </td> <td> </td> <td> </td> <td class="text-center" colspan="2"><b>Area</b></td> <td> </td> <td> </td> </tr> <tr> <td class="text-center"><b>#</b></td> <td class="text-center"><b>Abbrv</b></td> <td><b>State</b></td> <td><b>Sqr Miles</b></td> <td><b>Sqr Kms</b></td> <td><b>Capital</b></td> <td><b>Region</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<char, CountriesStatistics2.Models.State> special in specials) { <tr> <td class="text-center"><b>@j</b></td> <td class="text-center">@special.Value.Abbreviation</td> <td>@special.Value.StateName</td> <td class="text-right">@special.Value.AreaSqrMiles</td> <td class="text-right">@special.Value.AreaSqrKms</td> <td>@special.Value.Capital</td> <td>@special.Value.Region</td> </tr> j++; } </table> </div> <div style="width: 300px; margin: auto; margin-bottom: 4em"> <h2 class="text-center">Regions</h2> <table style="width: 100%" border="3"> <tr> <td class="text-center"><b>#</b></td> <td><b>Region</b></td> </tr> @foreach (System.Collections.Generic.KeyValuePair<int, string> region in regions) { <tr> <td>@region.Key</td> <td>@region.Value</td> </tr> } </table> </div>
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 is an example:
@{
ViewBag.Title = "State Search";
}
<h2>State Search</h2>
@{
string strLetter = string.Empty;
string strMessage = string.Empty;
CountriesStatistics2.Controllers.VenezuelaController vc = new CountriesStatistics2.Controllers.VenezuelaController();
System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> states = vc.States;
if (IsPost)
{
strLetter = Request["LetterEntered"].ToLower().Replace(".", "").Replace(" ", "");
char letter = strLetter[0];
bool found = states.ContainsKey(letter);
if (found == true)
{
strMessage = "There is a state with that abbreviation.";
}
else
{
strMessage = "There is no state that uses that abbreviation.";
}
}
}
@using (Html.BeginForm())
{
<table style="width: 520px;">
<tr>
<td style="width: 225px;">Enter the last letter of a state abbreviation:</td>
<td style="width: 80px;">@Html.TextBox("LetterEntered", @strLetter, new { style = "width: 50px;" })</td>
<td><input type="submit" name="btnFind" value="Find" style="width: 50px;" /></td>
</tr>
</table>
<p>@strMessage</p>
}
</div>
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:
@{
ViewBag.Title = "State Search";
}
<h2>State Search</h2>
@{
string strMessage = string.Empty;
string strNameEntered = string.Empty;
CountriesStatistics2.Models.State entity = null;
CountriesStatistics2.Controllers.VenezuelaController vc = new CountriesStatistics2.Controllers.VenezuelaController();
System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> states = vc.States;
if (IsPost)
{
entity = new CountriesStatistics2.Models.State();
entity.Name = Request["NameEntered"];
bool found = states.ContainsValue(entity);
if (found == true)
{
strNameEntered = entity.Name;
strMessage = "There is a state with that name.";
}
else
{
strMessage = "There is no state that uses that name.";
}
}
}
@using (Html.BeginForm())
{
<table style="width: 520px;">
<tr>
<td>Enter State Name:</td>
<td>@Html.TextBox("NameEntered", @strNameEntered)</td>
<td><input type="submit" name="btnFind" value="Find" style="width: 150px;" /></td>
</tr>
</table>
<p>@strMessage</p>
}
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.
Practical Learning: Getting the Value of a Key
@{ ViewBag.Title = "State Search"; } @{ string stLetter = string.Empty; string strMessage = string.Empty; string strAbbreviation = string.Empty; CountriesStatistics2.Models.State entity = new CountriesStatistics2.Models.State(); CountriesStatistics2.Controllers.VenezuelaController vc = new CountriesStatistics2.Controllers.VenezuelaController(); System.Collections.Generic.Dictionary<char, CountriesStatistics2.Models.State> states = vc.States; if (IsPost) { try { stLetter = Request["LetterEntered"].ToLower().Trim(); bool found = states.TryGetValue(stLetter[0], out entity); if (found == true) { strAbbreviation = "VE-" + stLetter.ToUpper(); } else { entity = new CountriesStatistics2.Models.State(); throw new System.NullReferenceException("There is no state that abbreviation in the collection."); } } catch(System.NullReferenceException nre) { strMessage = nre.Message; } catch (Exception exc) { strMessage = exc.Message; } } } <div align="center"> <h2>State Search</h2> @using (Html.BeginForm()) { <table style="width: 520px;"> <tr> <td style="width: 225px;">Enter the last letter of a state/area abbreviation:</td> <td style="width: 80px;">@Html.TextBox("LetterEntered", "", new { style = "width: 50px;" })</td> <td><input type="submit" name="btnFind" value="Find" style="width: 50px;" /></td> </tr> </table> <table style="width: 520px;"> <tr> <td style="width: 140px;">State:</td> <td style="width: 50px;">@Html.TextBox("Abbreviation", @strAbbreviation, new { style = "width: 50px;" })</td> <td>@Html.TextBox("StateName", @entity.Name)</td> </tr> </table> <table style="width: 520px;"> <tr> <td style="width: 140px;">Area:</td> <td>@Html.TextBox("txtAreaSqrMiles", @entity.AreaSqrMiles, new { style = "width: 80px;" }) SqrMi @Html.TextBox("txtAreaSqrKms", @entity.AreaSqrKms, new { style = "width: 80px;" }) Km<sup>2</sup> </td> </tr> </table> <table style="width: 520px;"> <tr> <td style="width: 140px;">Capital:</td> <td>@Html.TextBox("txtCapital", @entity.Capital)</td> </tr> <tr> <td style="width: 140px;">Region:</td> <td>@Html.TextBox("txtCapital", @entity.Region)</td> </tr> </table> <p>@strMessage</p> } </div>
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:
<!DOCTYPE html>
<html>
<head>
<title>Customers Records</title>
</head>
<body>
<h2>Customers Records</h2>
@{
System.Collections.Hashtable customers = new System.Collections.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";
System.Collections.Hashtable clients = new System.Collections.Hashtable(customers);
clients.Add("G-4208-3529", "Government");
clients.Add("G-2720-2483", "Government");
clients.Add("G-7350-8074", "Government");
}
<ul>
@foreach (System.Collections.DictionaryEntry entry in clients)
{
<li>@entry.Key: @entry.Value</li>
}
</ul>
<h2>Customers Records</h2>
@{
clients.Remove("L-975-275-M");
}
<ul>
@foreach (System.Collections.DictionaryEntry entry in clients)
{
<li>@entry.Key: @entry.Value</li>
}
</ul>
</body>
</html>
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 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 classe.
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.
Practical Learning: Completing the Lesson
using System;
namespace CountriesStatistics2.Models
{
public class State : IAbbreviated,
IGovernmentEntity,
IComparable
{
// From the IAbbreviated interface
public string Abbreviation { get; set; }
// From the IGovernmentEntity interface
public string Name { get; set; }
public int Area
{
get { return AreaSqrMiles; }
set { }
}
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;
}
}
}
@{ ViewBag.Title = "Commonwealth of Australia"; } <div align="center"> <h2 class="text-center">Commonwealth of Australia</h2> @{ string[] WesternAustralia = new string[1] { "Perth" }; CountriesStatistics2.Models.State[] states = new CountriesStatistics2.Models.State[6]; states[0] = new CountriesStatistics2.Models.State() { Abbreviation = "WA", Name = "Western Australia", AreaSqrKms = 2529875, Capital = "Perth" }; states[0].SignificanCities = WesternAustralia; states[1] = new CountriesStatistics2.Models.State() { Abbreviation = "SA", Name = "South Australia", AreaSqrKms = 983482, Capital = "Adelaide" }; states[1].SignificanCities = new string[] { "Adelaide" }; states[2] = new CountriesStatistics2.Models.State() { Abbreviation = "QLD", Name = "Queensland", AreaSqrKms = 1730648, Capital = "Brisbane", SignificanCities = new string[] { "Brisbane", "Sunshine Coast", "Gold Coast", "Townsville", "Cairns", "Toowoomba" } }; states[3] = new CountriesStatistics2.Models.State() { Abbreviation = "NSW", Name = "New South Wales", AreaSqrKms = 800642, Capital = "Sydney", SignificanCities = new string[] { "Sydney", "Newcastle", "Queanbeyan", "Tweed Heads", "Maitland", "Wollongong", "Albury" } }; states[4] = new CountriesStatistics2.Models.State() { Abbreviation = "VIC", Name = "Victoria", AreaSqrKms = 227416, Capital = "Melbourne" }; states[5] = new CountriesStatistics2.Models.State() { Abbreviation = "TAS", Name = "Tasmania", AreaSqrKms = 68401, Capital = "Hobart" }; states[4].SignificanCities = new string[] { "Melbourne", "Geelong", "Ballarat", "Bendigo", "Wodonga" }; states[5].SignificanCities = new string[2]; states[5].SignificanCities[0] = "Hobart"; states[5].SignificanCities[1] = "Launceston"; } <table border="6" style="width: 660px" cellpadding="2" cellspacing="1"> <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> @for (int counter = 0; counter < states.Length - 1; counter++) { <tr> <td class="text-center">@states[counter].Abbreviation</td> <td>@states[counter].StateName</td> <td class="text-right">@states[counter].AreaSqrKms Km<sup>2</sup></td> <td>@states[counter].Capital</td> <td> @for (int city = 0; city <= @states[counter].SignificanCities.Length - 1; city++) { @states[counter].SignificanCities[city]<br />; } </td> </tr> } </table> </div>
namespace CountriesStatistics2.Models { public class Collector { // This is the size of the collection private int size; private string[] items; #region This section is used to set up the collection public Collector() { size = 0; items = new string[26]; } // This represents the number of items in the collection public int Count { get { return size; } } #endregion #region Operations on the collection // Adds a new item to the list if the list is not full // Increases the number of items in the list // Returns true if the item was added, otherwise returns false public bool Add(string item) { // Make sure the list is not yet full if (size < 26) { // Since the list is not full, add the item at the end items[size] = item; // Increase the count and return the new position size++; // Indicate that the item was successfully added return true; } // If the item was not added, return false; return false; } // This method retrieves an item from the list based on the specified index public string Get(int pos) { // Make sure the index is in the range if (pos >= 0 && pos <= size) return items[pos]; // If the index was wrong, return 0 return string.Empty; } // Before performing this operation, check that // 1. The list is not full // 2. The specified position is in an allowable range // Insert a new item at a specified position in the list. // After the new item is inserted, the count is increased public bool Insert(string itm, int pos) { // Check that the item can be added to the list if (size < Count && pos >= 0 && pos <= size) { // Since there is room, // starting from the end of the list to the new position, // push each item to the next or up // to create room for the new item for (int i = size; i > pos - 1; i--) items[i + 1] = items[i]; // Now that we have room, put the new item in the position created items[pos] = itm; // Since we have added a new item, increase the count size++; // Indicate that the operation was successful return true; } // Since the item could not be added, return false return false; } // This method removes an item from the list // First check that the specified position is valid //-- Delete the item at that position and decrease the count --// public bool Delete(int pos) { // Make sure the position specified is in the range if (pos >= 0 && pos <= size) { // Since there is room, starting at the specified position, // Replace each item by the next for (int i = pos; i < size; i++) items[i - 1] = items[i]; // Since an item has been removed, decrease the count size--; // Indicate that the operation was successful return true; } // Since the position was out of range, return false return false; } #endregion } }
@{ ViewBag.Title = "Brazil: States"; } <div align="center"> <h2 class="text-center">Brazil: States</h2> @{ CountriesStatistics2.Models.Collector states = new CountriesStatistics2.Models.Collector(); CountriesStatistics2.Models.Collector capitals = new CountriesStatistics2.Models.Collector(); CountriesStatistics2.Models.Collector areasSqrKms = new CountriesStatistics2.Models.Collector(); CountriesStatistics2.Models.Collector areasSqrMls = new CountriesStatistics2.Models.Collector(); CountriesStatistics2.Models.Collector abbreviations = new CountriesStatistics2.Models.Collector(); states.Add("Pernambuco"); abbreviations.Add("PE"); capitals.Add("Recife"); areasSqrKms.Add("98,311.6"); areasSqrMls.Add("37,958"); states.Add("Maranhão"); abbreviations.Add("MA"); capitals.Add("São Luís"); areasSqrKms.Add("331,983.3"); areasSqrMls.Add("128,180"); states.Add("Paraíba"); abbreviations.Add("PB"); capitals.Add("João Pessoa"); areasSqrKms.Add("56,439.8"); areasSqrMls.Add("21,792"); states.Add("Acre"); abbreviations.Add("AC"); capitals.Add("Rio Branco"); areasSqrKms.Add("152,581.4"); areasSqrMls.Add("58,912"); states.Add("Rio Grande do Sul"); abbreviations.Add("RS"); capitals.Add("Porto Alegre"); areasSqrKms.Add("281,748.5"); areasSqrMls.Add("108,780"); states.Add("Distrito Federal"); abbreviations.Add("DF"); capitals.Add("Brasília"); areasSqrKms.Add("5,822.1"); areasSqrMls.Add("2,249.9"); states.Add("Tocantins"); abbreviations.Add("TO"); capitals.Add("Palmas"); areasSqrKms.Add("277,620.9"); areasSqrMls.Add("107,190"); states.Add("Ceará"); abbreviations.Add("CE"); capitals.Add("Fortaleza"); areasSqrKms.Add("148,825.6"); areasSqrMls.Add("57,462"); states.Add("Rio de Janeiro"); abbreviations.Add("RJ"); capitals.Add("Rio de Janeiro"); areasSqrKms.Add("43,696.1"); areasSqrMls.Add("16,871"); states.Add("Amazonas"); abbreviations.Add("AM"); capitals.Add("Manaus"); areasSqrKms.Add("1,570,745.7"); areasSqrMls.Add("606,470"); states.Add("Rio Grande do Norte"); abbreviations.Add("RN"); capitals.Add("Natal"); areasSqrKms.Add("52,796.8"); areasSqrMls.Add("20,385"); states.Add("São Paulo"); abbreviations.Add("SP"); capitals.Add("São Paulo"); areasSqrKms.Add("248,209.4"); areasSqrMls.Add("95,834"); states.Add("Mato Grosso do Sul"); abbreviations.Add("MS"); capitals.Add("Campo Grande"); areasSqrKms.Add("357,125"); areasSqrMls.Add("137,890"); states.Add("Roraima"); abbreviations.Add("RR"); capitals.Add("Boa Vista"); areasSqrKms.Add("224,299"); areasSqrMls.Add("86,602"); states.Add("Goiás"); abbreviations.Add("GO"); capitals.Add("Goiânia"); areasSqrKms.Add("340,086.7"); areasSqrMls.Add("131,310"); states.Add("Alagoas"); abbreviations.Add("AL"); capitals.Add("Maceió"); areasSqrKms.Add("27,767.7"); areasSqrMls.Add("10,721"); states.Add("Sergipe"); abbreviations.Add("SE"); capitals.Add("Aracaju"); areasSqrKms.Add("21,910.3"); areasSqrMls.Add("8,459.6"); states.Add("Rondônia"); abbreviations.Add("RO"); capitals.Add("Porto Velho"); areasSqrKms.Add("237,576.2"); areasSqrMls.Add("91,729"); states.Add("Mato Grosso"); abbreviations.Add("MT"); capitals.Add("Cuiabá"); areasSqrKms.Add("903,357.9"); areasSqrMls.Add("348,790"); states.Add("Paraná"); abbreviations.Add("PR"); capitals.Add("Curitiba"); areasSqrKms.Add("199,314.9"); areasSqrMls.Add("76,956"); states.Add("Santa Catarina"); abbreviations.Add("SC"); capitals.Add("Florianópolis"); areasSqrKms.Add("95,346.2"); areasSqrMls.Add("36,813"); states.Add("Minas Gerais"); abbreviations.Add("MG"); capitals.Add("Belo Horizonte"); areasSqrKms.Add("586,528.3"); areasSqrMls.Add("226,460"); states.Add("Bahia"); abbreviations.Add("BA"); capitals.Add("Salvador"); areasSqrKms.Add("564,692.7"); areasSqrMls.Add("218,030"); states.Add("Piauí"); abbreviations.Add("PI"); capitals.Add("Teresina"); areasSqrKms.Add("251,529.2"); areasSqrMls.Add("97,726"); states.Add("Amapá"); abbreviations.Add("AP"); capitals.Add("Macapá"); areasSqrKms.Add("142,814.6"); areasSqrMls.Add("55,151"); states.Add("Pará"); abbreviations.Add("PA"); capitals.Add("Belém"); areasSqrKms.Add("1,247,689.5"); areasSqrMls.Add("481,740"); states.Add("Espírito Santo"); abbreviations.Add("ES"); capitals.Add("Vitória"); areasSqrKms.Add("46,077.5"); areasSqrMls.Add("17,791"); } <table border="4"> <tr> <td style="width: 60px; text-align: center; font-weight: 600">#</td> <td style="width: 150px"><b>states Name</b></td> <td style="width: 60px; text-align: center"><b>Abbrv</b></td> <td style="width: 100px; text-align: right"><b>Area (Kms<sup>2</sup>)</b></td> <td style="width: 120px; text-align: right"><b>Area (Sqr Miles)</b></td> <td style="font-weight: 600">Capital</td> </tr> @for (int i = 0; i < states.Count; i++) { <tr> <td style="text-align: center">@(i + 1)</td> <td>@states.Get(i)</td> <td style="text-align: center">@abbreviations.Get(i)</td> <td style="text-align: right">@areasSqrKms.Get(i)</td> <td style="text-align: right">@areasSqrMls.Get(i)</td> <td>@capitals.Get(i)</td> </tr> } </table> </div>
using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class GermanyController : Controller { public int[] Areas; public string[] States; public string[] Capitals; public string[] Abbreviations; public GermanyController() { Abbreviations = new string[] { "TH", "SL", "NW", "HH", "RP", "NI", "SH", "BB", "HE", "BE", "ST", "BW", "BY", "SN", "HB", "MV" }; States = new string[] { "Saarland", "North Rhine-Westphalia", "Thuringia", "Hamburg", "Rhineland-Palatinate", "Lower Saxony", "Schleswig-Holstein", "Brandenburg", "Hesse", "Berlin", "Saxony-Anhalt", "Baden-Württemberg", "Bavaria", "Saxony", "Bremen", "Mecklenburg-Vorpommern" }; Areas = new int[] { 16172, 2569, 34085, 755, 19853, 47609, 15799, 29479, 21115, 892, 20446, 35752, 70552, 18416, 419, 23180 }; Capitals = new string[] { "Saarbrücken", "Düsseldorf", "Erfurt", "", "Mainz", "Hanover", "Kiel", "", "Wiesbaden", "Stuttgart", "Magdeburg", "Munich", "Potsdam", "Dresden", "Bremen", "Schwerin" }; } // GET: Germany public ActionResult Index() { return View(); } // GET: Germany/StateSearch public ActionResult StateSearch() { return View(); } } }
@{ ViewBag.Title = "Germany"; } <h2 class="text-center">Germany</h2> @{ int i = 0; CountriesStatistics2.Controllers.GermanyController gc = new CountriesStatistics2.Controllers.GermanyController(); } <div align="center"> <table border="6" style="width: 500px" cellpadding="2" cellspacing="1"> <tr> <td class="text-center short-text">#</td> <td class="text-center"><b>Abbrv</b></td> <td><b>State Name</b></td> <td class="text-right"><b>Area</b></td> <td><b>Capital</b></td> </tr> @while (i < gc.Abbreviations.Length) { <tr> <td class="text-center">@(i + 1)</td> <td class="text-center">@gc.Abbreviations[i]</td> <td>@gc.States[i]</td> <td class="text-right">@gc.Areas[i] Km<sup>2</sup></td> <td>@gc.Capitals[i]</td> </tr> i++; } </table> </div> <p class="text-center">@Html.ActionLink("State Search", "StateSearch")</p>
@{ ViewBag.Title = "State Search"; } <h2>State Search</h2> @{ int iArea = 0; bool found = false; string strErrorMessage = ""; string strCapital = string.Empty; string strStateName = string.Empty; string strAbbreviation = string.Empty; string strStateLetters = string.Empty; CountriesStatistics2.Controllers.GermanyController gc = new CountriesStatistics2.Controllers.GermanyController(); if (IsPost) { if (string.IsNullOrWhiteSpace(Request["txtStateLetters"].ToString())) { strErrorMessage = "You must type a 2-letter abbreviation for a state"; } else { strStateLetters = Request["txtStateLetters"].ToString(); string strReduced = strStateLetters.ToUpper().Replace(" ", "").Replace(".", ""); for (int i = 0; i < 16; i++) { if (strReduced.Equals(gc.Abbreviations[i])) { iArea = gc.Areas[i]; strStateName = gc.States[i]; strCapital = gc.Capitals[i]; strAbbreviation = gc.Abbreviations[i]; found = true; break; } } } if (found == false) { strErrorMessage = "There is no state with those letters."; } } } @using (Html.BeginForm()) { <table style="width: 320px;"> <tr> <td class="left-col">State Letters:</td> <td> @Html.TextBox("txtStateLetters", "", new { style = "width: 60px" }) <input type="submit" name="btnFind" value="Find" class="left-col" /> </td> </tr> <tr> <td>State:</td> <td> @Html.TextBox("txtAbbreviation", @strAbbreviation, new { style = "width: 40px" }) @Html.TextBox("txtStateName", @strStateName) </td> </tr> <tr> <td>Area:</td> <td>@Html.TextBox("txtArea", @iArea, new { @class = "medium-text" }) Km<sup>2</sup></td> </tr> <tr> <td>Capital:</td> <td>@Html.TextBox("txtCapital", @strCapital)</td> </tr> </table> <p>@strErrorMessage</p> } <p class="text-center">@Html.ActionLink("Home", "Index")</p>
@{ ViewBag.Title = "United Mexican States"; } <h2 class="text-center">United Mexican States</h2> @{ string[] states = new string[31]; states[0] = "Guanajuato"; states[1] = "Tamaulipas"; states[2] = "Michoacán"; states[3] = "Coahuila"; states[4] = "Chihuahua"; states[5] = "Baja California Sur"; states[6] = "Nayarit"; states[7] = "Puebla"; states[8] = "Oaxaca"; states[9] = "Morelos"; states[10] = "Sonora"; states[11] = "Aguascalientes"; states[12] = "Baja California"; states[13] = "Tabasco"; states[14] = "Jalisco"; states[15] = "México"; states[16] = "Guerrero"; states[17] = "Colima"; states[18] = "Zacatecas"; states[19] = "Sinaloa"; states[20] = "Campeche"; states[21] = "Quintana Roo"; states[22] = "Nuevo León"; states[23] = "Hidalgo"; states[24] = "Tlaxcala"; states[25] = "Yucatán"; states[26] = "Querétaro"; states[27] = "Veracruz"; states[28] = "San Luis Potosí"; states[29] = "Durango"; states[30] = "Chiapas"; string[] capitals = new string[] { "Guanajuato", "Ciudad Victoria", "Morelia", "Saltillo", "Chihuahua", "La Paz", "Tepic", "Puebla de Zaragoza", "Oaxaca de Juárez", "Cuernavaca", "Hermosillo", "Aguascalientes", "Mexicali", "Villahermosa", "Guadalajara", "Toluca de Lerdo", "Chilpancingo de los Bravo", "Colima", "Zacatecas", "Culiacán", "San Francisco de Campeche", "Chetumal", "Monterrey", "Pachuca", "Tlaxcala", "Mérida", "Santiago de Querétaro", "Xalapa", "San Luis Potosí", "Victoria de Durango", "Tuxtla Gutiérrez"}; int[] areasSqrKms = new int[] { 30608, 80175, 58643, 151563, 247455, 73922, 27815, 34290, 93793, 4893, 179503, 5618, 71446, 24738, 78599, 22357, 63621, 5625, 75539, 57377, 57924, 42361, 64220, 20846, 3991, 39612, 11684, 71820, 60983, 123451, 73289 }; int[] areasSqrMiles = new int[] { 11818, 30956, 22642, 58519, 95543, 28541, 10739, 13240, 36214, 1889, 69306, 2169, 27585, 9551, 30347, 8632, 24564, 2172, 29166, 22153, 22365, 16356, 24800, 8049, 1541, 15294, 4511, 27730, 23546, 47665, 28297 }; int[] ordersOfAdmissionToFederation = new int[] { 2, 14, 5, 16, 18, 31, 28, 4, 3, 27, 12, 24, 29, 13, 9, 1, 21, 23, 10, 20, 25, 30, 15, 26, 22, 8, 11, 7, 6, 17, 19 }; DateTime[] dateOfAdmissionToFederation = new DateTime[] { new DateTime(1823, 12, 20), new DateTime(1824, 2, 7), new DateTime(1823, 12, 22), new DateTime(1824, 5, 7), new DateTime(1824, 7, 6), new DateTime(1952, 1, 16), new DateTime(1917, 1, 26), new DateTime(1823, 12, 21), new DateTime(1823, 12, 21), new DateTime(1869, 4, 17), new DateTime(1824, 1, 10), new DateTime(1857, 2, 5), new DateTime(1952, 1, 16), new DateTime(1824, 2, 7), new DateTime(1823, 12, 23), new DateTime(1823, 12, 20), new DateTime(1849, 10, 27), new DateTime(1856, 9, 12), new DateTime(1823, 12, 23), new DateTime(1830, 10, 14), new DateTime(1863, 4, 29), new DateTime(1974, 10, 8), new DateTime(1824, 5, 7), new DateTime(1869, 1, 16), new DateTime(1856, 12, 9), new DateTime(1823, 12, 23), new DateTime(1823, 12, 23), new DateTime(1823, 12, 22), new DateTime(1823, 12, 22), new DateTime(1824, 5, 22), new DateTime(1824, 9, 14) }; } @{ int i = 0; } <div class="centralizer"> <table cellpadding="2" cellspacing="1" border="6"> <tr> <td class="text-center"> </td> <td> </td> <td colspan="2" class="text-center"><b>Area</b></td> <td colspan="2" class="text-center"><b>Admission to Federation</b></td> <td> </td> </tr> <tr> <td class="text-center short-text">#</td> <td><b>State Name</b></td> <td class="text-center"><b>Sqr Kms</b></td> <td class="text-center"><b>Sqr Miles</b></td> <td class="text-center"><b>Date</b></td> <td class="text-center"><b>Order</b></td> <td><b>Capital</b></td> </tr> @while (i < dateOfAdmissionToFederation.Length) { <tr> <td class="text-center">@(i + 1)</td> <td>@states[i]</td> <td class="text-right">@areasSqrKms[i]</td> <td class="text-right">@areasSqrMiles[i]</td> <td class="text-center">@dateOfAdmissionToFederation[i].ToString("yyyy-MMM-dd")</td> <td class="text-center">@ordersOfAdmissionToFederation[i]</td> <td>@capitals[i]</td> </tr> i++; } </table> </div>
using System; using System.Web.Mvc; namespace CountriesStatistics2.Controllers { public class UnitedStatesController : Controller { public string[] Regions; public Models.Federation[] States; public UnitedStatesController() { Regions = new string[] { "East North Central", "East South Central", "New England", "Mid-Atlantic", "Mountain", "Pacific", "South Atlantic", "West North Central", "West South Central" }; States = new Models.Federation[40]; States[0] = new Models.Federation() { Abbreviation = "RI", Name = "Rhode Island", Area = 1545, AreaSqrKms = 4002, AdmissionUnionDate = new DateTime(1790, 5, 29), AdmissionUnionOrder = 13, Capital = "Providence", Region = Regions[2] }; States[1] = new Models.Federation() { Abbreviation = "OH", Name = "Ohio", Area = 44828, AreaSqrKms = 116103, AdmissionUnionDate = new DateTime(1803, 3, 1), AdmissionUnionOrder = 17, Capital = "Columbus", Region = Regions[0] }; States[2] = new Models.Federation() { Abbreviation = "KY", Name = "Kentucky", Area = 40411, AreaSqrKms = 104665, AdmissionUnionDate = new DateTime(1792, 6, 1), AdmissionUnionOrder = 15, Capital = "Frankfort", Region = Regions[1] }; States[3] = new Models.Federation() { Abbreviation = "IA", Name = "Iowa", Area = 56276, AreaSqrKms = 145754, AdmissionUnionDate = new DateTime(1846, 12, 28), AdmissionUnionOrder = 29, Capital = "Des Moines", Region = Regions[7] }; States[4] = new Models.Federation() { Abbreviation = "WI", Name = "Wisconsin", Area = 65503, AreaSqrKms = 169653, AdmissionUnionDate = new DateTime(1848, 5, 29), AdmissionUnionOrder = 30, Capital = "Madison", Region = Regions[0] }; States[5] = new Models.Federation() { Abbreviation = "VT", Name = "Vermont", Area = 9615, AreaSqrKms = 24903, AdmissionUnionDate = new DateTime(1791, 3, 4), AdmissionUnionOrder = 14, Capital = "Montpelier", Region = Regions[2] }; States[6] = new Models.Federation() { Abbreviation = "ID", Name = "Idaho", Area = 83574, AreaSqrKms = 216456, AdmissionUnionDate = new DateTime(1890, 7, 3), AdmissionUnionOrder = 43, Capital = "Boise", Region = Regions[4] }; States[7] = new Models.Federation() { Abbreviation = "ME", Name = "Maine", Area = 35387, AreaSqrKms = 91653, AdmissionUnionDate = new DateTime(1820, 3, 15), AdmissionUnionOrder = 23, Capital = "Augusta", Region = Regions[2] }; States[8] = new Models.Federation() { Abbreviation = "OR", Name = "Oregon", Area = 98386, AreaSqrKms = 254819, AdmissionUnionDate = new DateTime(1859, 2, 14), AdmissionUnionOrder = 33, Capital = "Salem", Region = Regions[5] }; States[9] = new Models.Federation() { Abbreviation = "ND", Name = "North Dakota", Area = 70704, AreaSqrKms = 183123, AdmissionUnionDate = new DateTime(1889, 11, 2), AdmissionUnionOrder = 39, Capital = "Bismarck", Region = Regions[7] }; States[10] = new Models.Federation() { Abbreviation = "IN", Name = "Indiana", Area = 36420, AreaSqrKms = 94328, AdmissionUnionDate = new DateTime(1816, 12, 11), AdmissionUnionOrder = 19, Capital = "Indianapolis", Region = Regions[0] }; States[11] = new Models.Federation() { Abbreviation = "MS", Name = "Mississippi", Area = 48434, AreaSqrKms = 125443, AdmissionUnionDate = new DateTime(1817, 12, 10), AdmissionUnionOrder = 20, Capital = "Jackson", Region = Regions[1] }; States[12] = new Models.Federation() { Abbreviation = "TX", Name = "Texas", Area = 268601, AreaSqrKms = 695676, AdmissionUnionDate = new DateTime(1845, 12, 29), AdmissionUnionOrder = 28, Capital = "Austin", Region = Regions[8] }; States[13] = new Models.Federation() { Abbreviation = "MT", Name = "Montana", Area = 147046, AreaSqrKms = 380850, AdmissionUnionDate = new DateTime(1889, 11, 8), AdmissionUnionOrder = 41, Capital = "Helena", Region = Regions[4] }; States[14] = new Models.Federation() { Abbreviation = "NC", Name = "North Carolina", Area = 53821, AreaSqrKms = 139397, AdmissionUnionDate = new DateTime(1789, 11, 21), AdmissionUnionOrder = 12, Capital = "Raleigh", Region = Regions[6] }; States[15] = new Models.Federation() { Abbreviation = "TN", Name = "Tennessee", Area = 42146, AreaSqrKms = 109158, AdmissionUnionDate = new DateTime(1796, 6, 1), AdmissionUnionOrder = 16, Capital = "Nashville", Region = Regions[1] }; States[16] = new Models.Federation() { Abbreviation = "NE", Name = "Nebraska", Area = 77358, AreaSqrKms = 200358, AdmissionUnionDate = new DateTime(1867, 3, 1), AdmissionUnionOrder = 37, Capital = "Lincoln", Region = Regions[7] }; States[17] = new Models.Federation() { Abbreviation = "IL", Name = "Illinois", Area = 57918, AreaSqrKms = 150007, AdmissionUnionDate = new DateTime(1818, 12, 3), AdmissionUnionOrder = 21, Capital = "Springfield", Region = Regions[0] }; States[18] = new Models.Federation() { Abbreviation = "KS", Name = "Kansas", Area = 82282, AreaSqrKms = 213110, AdmissionUnionDate = new DateTime(1861, 1, 29), AdmissionUnionOrder = 34, Capital = "Topeka", Region = Regions[7] }; States[19] = new Models.Federation() { Abbreviation = "NH", Name = "New Hampshire", Area = 9351, AreaSqrKms = 24219, AdmissionUnionDate = new DateTime(1788, 6, 21), AdmissionUnionOrder = 9, Capital = "Concord", Region = Regions[2] }; States[20] = new Models.Federation() { Abbreviation = "DE", Name = "Delaware", Area = 2489, AreaSqrKms = 6447, AdmissionUnionDate = new DateTime(1787, 12, 7), AdmissionUnionOrder = 1, Capital = "Dover", Region = Regions[6] }; States[21] = new Models.Federation() { Abbreviation = "NJ", Name = "New Jersey", Area = 8722, AreaSqrKms = 22590, AdmissionUnionDate = new DateTime(1787, 12, 18), AdmissionUnionOrder = 3, Capital = "Trenton", Region = Regions[3] }; States[22] = new Models.Federation() { Abbreviation = "AK", Name = "Alaska", Area = 656424, AreaSqrKms = 1700139, AdmissionUnionDate = new DateTime(1959, 1, 3), AdmissionUnionOrder = 49, Capital = "Juneau", Region = Regions[5] }; States[23] = new Models.Federation() { Abbreviation = "NM", Name = "New Mexico", Area = 121598, AreaSqrKms = 314939, AdmissionUnionDate = new DateTime(1912, 1, 6), AdmissionUnionOrder = 47, Capital = "Santa Fe", Region = Regions[4] }; States[24] = new Models.Federation() { Abbreviation = "NY", Name = "New York", Area = 54475, AreaSqrKms = 141089, AdmissionUnionDate = new DateTime(1788, 7, 26), AdmissionUnionOrder = 11, Capital = "Albany", Region = Regions[3] }; States[25] = new Models.Federation() { Abbreviation = "CA", Name = "California", Area = 163707, AreaSqrKms = 424002, AdmissionUnionDate = new DateTime(1850, 9, 9), AdmissionUnionOrder = 31, Capital = "Sacramento", Region = Regions[5] }; States[26] = new Models.Federation() { Abbreviation = "MO", Name = "Missouri", Area = 69709, AreaSqrKms = 180546, AdmissionUnionDate = new DateTime(1821, 8, 10), AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = Regions[7] }; States[27] = new Models.Federation() { Abbreviation = "OK", Name = "Oklahoma", Area = 69903, AreaSqrKms = 181049, AdmissionUnionDate = new DateTime(1907, 11, 16), AdmissionUnionOrder = 46, Capital = "Oklahoma City", Region = Regions[8] }; States[28] = new Models.Federation() { Abbreviation = "PA", Name = "Pennsylvania", Area = 46058, AreaSqrKms = 119291, AdmissionUnionDate = new DateTime(1787, 12, 12), AdmissionUnionOrder = 2, Capital = "Harrisburg", Region = Regions[3] }; States[29] = new Models.Federation() { Abbreviation = "SC", Name = "South Carolina", Area = 32007, AreaSqrKms = 82898, AdmissionUnionDate = new DateTime(1788, 5, 23), AdmissionUnionOrder = 8, Capital = "Columbia", Region = Regions[6] }; States[30] = new Models.Federation() { Abbreviation = "WY", Name = "Wyoming", Area = 97818, AreaSqrKms = 253349, AdmissionUnionDate = new DateTime(1890 , 7, 10), AdmissionUnionOrder = 44, Capital = "Cheyenne", Region = Regions[4] }; States[31] = new Models.Federation() { Abbreviation = "SD", Name = "South Dakota", Area = 77122, AreaSqrKms = 199745, AdmissionUnionDate = new DateTime(1889, 11, 2), AdmissionUnionOrder = 40, Capital = "Pierre", Region = Regions[7] }; States[32] = new Models.Federation() { Abbreviation = "UT", Name = "Utah", Area = 84904, AreaSqrKms = 219902, AdmissionUnionDate = new DateTime(1896, 1, 4), AdmissionUnionOrder = 45, Capital = "Salt Lake City", Region = Regions[4] }; States[33] = new Models.Federation() { Abbreviation = "AL", Name = "Alabama", Area = 52423, AreaSqrKms = 135775, AdmissionUnionDate = new DateTime(1819, 12, 14), AdmissionUnionOrder = 22, Capital = "Montgomery", Region = Regions[1] }; States[34] = new Models.Federation() { Abbreviation = "VT", Name = "Vermont", Area = 9615, AreaSqrKms = 24903, AdmissionUnionDate = new DateTime(1791, 3, 4), AdmissionUnionOrder = 14, Capital = "Montpelier", Region = Regions[2] }; States[35] = new Models.Federation() { Abbreviation = "AR", Name = "Arkansas", Area = 53182, AreaSqrKms = 137742, AdmissionUnionDate = new DateTime(1836, 6, 15), AdmissionUnionOrder = 25, Capital = "Little Rock", Region = Regions[8] }; States[36] = new Models.Federation() { Abbreviation = "WA", Name = "Washington", Area = 71303, AreaSqrKms = 184674, AdmissionUnionDate = new DateTime(1889, 11, 11), AdmissionUnionOrder = 42, Capital = "Olympia", Region = Regions[5] }; States[37] = new Models.Federation() { Abbreviation = "AZ", Name = "Arizona", Area = 114006, AreaSqrKms = 295276, AdmissionUnionDate = new DateTime(1912, 2, 14), AdmissionUnionOrder = 48, Capital = "Phoenix", Region = Regions[4] }; States[38] = new Models.Federation() { Abbreviation = "WV", Name = "West Virginia", Area = 24231, AreaSqrKms = 62759, AdmissionUnionDate = new DateTime(1863, 6, 20), AdmissionUnionOrder = 35, Capital = "Charleston", Region = Regions[6] }; States[39] = new Models.Federation() { Abbreviation = "LA", Name = "Louisiana", Area = 51844, AreaSqrKms = 134275, AdmissionUnionDate = new DateTime(1812, 4, 30), AdmissionUnionOrder = 18, Capital = "Baton Rouge", Region = Regions[8] }; Array.Resize(ref States, States.Length + 5); States[40] = new Models.Federation() { Abbreviation = "MA", Name = "Massachusetts", Area = 10555, AreaSqrKms = 27337, AdmissionUnionDate = new DateTime(1788, 2, 6), AdmissionUnionOrder = 6, Capital = "Boston", Region = Regions[2] }; States[41] = new Models.Federation() { Abbreviation = "FL", Name = "Florida", Area = 65758, AreaSqrKms = 170313, AdmissionUnionDate = new DateTime(1845, 3, 3), AdmissionUnionOrder = 27, Capital = "Tallahassee", Region = Regions[6] }; States[42] = new Models.Federation() { Abbreviation = "GA", Name = "Georgia", Area = 59441, AreaSqrKms = 153953, AdmissionUnionDate = new DateTime(1788, 1, 2), AdmissionUnionOrder = 4, Capital = "Atlanta", Region = Regions[6] }; States[43] = new Models.Federation() { Abbreviation = "HI", Name = "Hawaii", Area = 10932, AreaSqrKms = 28313, AdmissionUnionDate = new DateTime(1959, 8, 21), AdmissionUnionOrder = 50, Capital = "Honolulu", Region = Regions[5] }; States[44] = new Models.Federation() { Abbreviation = "MD", Name = "Maryland", Area = 12407, AreaSqrKms = 32135, AdmissionUnionDate = new DateTime(1788, 4, 28), AdmissionUnionOrder = 7, Capital = "Annapolis", Region = Regions[6] }; Models.Federation[] temporary = new Models.Federation[States.Length + 5]; Array.Copy(States, temporary, States.Length); States = temporary; States[45] = new Models.Federation() { Abbreviation = "CO", Name = "Colorado", Area = 104100, AreaSqrKms = 269620, AdmissionUnionDate = new DateTime(1876, 8, 1), AdmissionUnionOrder = 38, Capital = "Denver", Region = Regions[4] }; States[46] = new Models.Federation() { Abbreviation = "MI", Name = "Michigan", Area = 98810, AreaSqrKms = 250738, AdmissionUnionDate = new DateTime(1837, 1, 26), AdmissionUnionOrder = 26, Capital = "Lansing", Region = Regions[0] }; States[47] = new Models.Federation() { Abbreviation = "MN", Name = "Minnesota", Area = 86943, AreaSqrKms = 225182, AdmissionUnionDate = new DateTime(1858, 5, 11), AdmissionUnionOrder = 32, Capital = "Saint Paul", Region = Regions[7] }; States[48] = new Models.Federation() { Abbreviation = "CT", Name = "Connecticut", Area = 5544, AreaSqrKms = 14358, AdmissionUnionDate = new DateTime(1788, 1, 9), AdmissionUnionOrder = 5, Capital = "Hartford", Region = Regions[3] }; States[49] = new Models.Federation() { Abbreviation = "NV", Name = "Nevada", Area = 110567, AreaSqrKms = 286368, AdmissionUnionDate = new DateTime(1864, 10, 31), AdmissionUnionOrder = 36, Capital = "Frankfort", Region = Regions[4] }; } // GET: UnitedStates public ActionResult Index() { return View(); } // GET: UnitedStates/StatesList public ActionResult StatesList() { return View(); } } }
@{ ViewBag.Title = "United States of America"; } <h2 class="text-center">United States of America</h2> @{ int counter = 0; CountriesStatistics2.Controllers.UnitedStatesController usc = new CountriesStatistics2.Controllers.UnitedStatesController(); if (IsPost) { Array.Sort(usc.States); } } @using (Html.BeginForm()) { <p class="text-center"><input type="submit" name="btnSubmit" value="Sort by State Name" /></p> <table border="6" style="width: 100%; margin-bottom: 4em" cellpadding="2" cellspacing="1"> <tr> <td> </td> <td> </td> <td> </td> <td colspan="2" class="text-center"><b>Area</b></td> <td colspan="2" class="text-center"><b>Admission to Union</b></td> <td> </td> <td> </td> </tr> <tr> <td class="text-center"><b>#</b></td> <td class="text-center"><b>Abbrv</b></td> <td class="text-center"><b>State Name</b></td> <td class="text-center"><b>Sqr Miles</b></td> <td class="text-center"><b>Km<sup>2</sup></b></td> <td class="text-center"><b>Date</b></td> <td class="text-center"><b>Order</b></td> <td><b>Capital</b></td> <td><b>Region</b></td> </tr> @while (counter <= usc.States.Length - 1) { <tr> <td class="text-center">@(counter + 1)</td> <td class="text-center">@usc.States[counter].Abbreviation</td> <td>@usc.States[counter].StateName</td> <td class="text-right">@usc.States[counter].AreaSqrMiles</td> <td class="text-right">@usc.States[counter].AreaSqrKms</td> <td class="text-center">@usc.States[counter].AdmissionUnionDate.ToShortDateString()</td> <td class="text-center">@usc.States[counter].AdmissionUnionOrder</td> <td>@usc.States[counter].Capital</td> <td>@usc.States[counter].Region</td> </tr> counter++; } </table> }
|
||
Previous | Copyright © 2011-2021, FunctionX | Next |
|