Introduction to Built-In Collections Classes
Introduction to Built-In Collections Classes
A Name/Value Collection
Introduction
To provide a special type of a dictionary-based collection, the System.Collections.Specialized namespace defines a class named NameValueCollection:
[SerializableAttribute] public class NameValueCollection : NameObjectCollectionBase
NameValueCollection is a collection class that uses combinations of strings for each item. As is the case for all dictionary-based collections, the NameValueCollection class uses combinations of key/value pairs, or rather name/value pairs.
Adding an Item to a Name/Value Collection
As is the case for most collection classes, the method to add an item to a NameValueCollection list is named Add. It comes in two versions. One version is used to add an existing NameValueCollection list to the collection. The other classic version uses the following syntax:
public virtual void Add(string name, string value);
When calling this method, pass two strings as arguments. The first argument will become the key and the second argument as value. Here is an example of calling this method:
using System.Web.Mvc; using System.Collections.Specialized; namespace Exercises.Controllers { public class BusinessController : Controller { // GET: Business public ActionResult Index() { NameValueCollection collegeMajors = new NameValueCollection(); collegeMajors.Add("CMSC", "Computer Science"); collegeMajors.Add("IFSM", "Information Systems Management"); collegeMajors.Add("PSAD", "Public Safety Administration"); collegeMajors.Add("GRCO", "Graphic Communication"); return View(); } } }
Accessing an Item from a Name/Value Collection by Name
To give you access to its items, the NameValueCollection class is equipped with a read-only indexed property that is overloaded with two versions. One of the versions uses the following syntax:
public string this[string name] { get; set; }
When using this version, you should pass an existing name. Here is an example:
using System.Web.Mvc;
using System.Collections.Specialized;
namespace ModelingExercise1.Controllers
{
public class BusinessController : Controller
{
// GET: Business
public ActionResult Index()
{
NameValueCollection collegeMajors = new NameValueCollection();
collegeMajors.Add("CMSC", "Computer Science");
collegeMajors.Add("IFSM", "Information Systems Management");
collegeMajors.Add("PSAD", "Public Safety Administration");
collegeMajors.Add("GRCO", "Graphic Communication");
string major = collegeMajors["PSAD"];
return View();
}
}
}
If you pass a valid name, this property produces the equivalent value. If pass a name that the compiler cannot find in the list, the property produces an empty value.
Accessing an Item from a Name/Value Collection by its Index
The items of a NameValueCollection list are stored in a 0-based indexed collection where the first value occupies the 0 position, the second value occupies the 1 position, and so on. To support this, the NameValueCollection class is equipped with the following version of its index property:
public string this[int index] { get; }
The integer-based based version allows you to pass a number as parameter. Here is an example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Specialized;
using System.Web.Mvc;
namespace ModelingExercise1.Controllers
{
public class BusinessController : Controller
{
// GET: Business
public ActionResult Index()
{
NameValueCollection collegeMajors = new NameValueCollection();
collegeMajors.Add("CMSC", "Computer Science");
collegeMajors.Add("IFSM", "Information Systems Management");
collegeMajors.Add("PSAD", "Public Safety Administration");
collegeMajors.Add("GRCO", "Graphic Communication");
string college = collegeMajors[2];
return View();
}
}
}
If you pass a positive index that is lower than the total number of items - 1, the compiler produces the equivalent value. If you pass a negative index or one that is higher than the total number of items, the compiler would throw a System.ArgumentOutOfRangeException exception.
Practical Learning: Introducing Built-In Collection Classes
body { } .content { width: 450px; margin: auto; } .summary { width: 300px; margin: auto; } .btnFormatting { height: 32px; width: 400px; } .tbxFormatting { width: 80px; } .main-title { margin: auto; width: 450px; border-bottom: 2px solid gray; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Payroll Evaluation :: @ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/Payroll.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("Payroll Evaluation", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p class="text-center">© @DateTime.Now.Year - Payroll Evaluation</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace PayrollPreparation18.Controllers { public class PayrollProcessingController : Controller { // GET: PayrollProcessing public ActionResult Index() { return View(); } // GET: PayrollStartUp public ActionResult PayrollStartUp() { return View(); } // GET: PayrollProcessing/PayrollPreparation public ActionResult PayrollPreparation() { return View(); } } }
A Form Collection
Introduction
Sometimes, to get the values from a view to a controller, you can pass the names of webcontrols to the necessary action/method. Here is an example:
using System.Web.Mvc;
namespace Exercises.Controllers
{
public class BusinessController : Controller
{
// GET: Business
public ActionResult Index()
{
return View();
}
public ActionResult CreateEmployeeRecord(string EmployeeNumber,
string FirstName,
string LastName,
string HourlySalary)
{
return View();
}
}
}
The .NET Framework provides a better solution. ASP.NET MVC makes it possible to consider all of the controls of a webpage as a group. To support the webcontrols of a view, ASP.NET MVC provides a class named FormCollection. It is defined in the System.Web.Mvc namespace. The FormCollection class is derived from the NameValueCollection class that we saw already:
public sealed class FormCollection : NameValueCollection, IValueProvider
Practical Learning: Introducing Built-In Collection Classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace PayrollPreparation18.Controllers
{
public class PayrollProcessingController : Controller
{
// GET: PayrollProcessing
public ActionResult Index()
{
return View();
}
// GET: PayrollStartUp
public ActionResult PayrollStartUp()
{
return View();
}
// GET: PayrollProcessing/PayrollPreparation
public ActionResult PayrollPreparation(string HourlySalary, string Monday, string Tuesday,
string Wednesday, string Thursday, string Friday)
{
return View();
}
}
}
@{ ViewBag.Title = "Payroll Start-Up"; } <h2 class="text-center">Payroll Start-Up</h2> <hr /> @using (Html.BeginForm("PayrollPreparation", "Home", FormMethod.Post, new { name = "frmPayrollPreparation" })) { <div class="content"> <table> <tr> <td>Hourly Salary:</td> <td> </td> </tr> </table> <hr /> <table> <tr> <td>Monday</td> <td>Tusday</td> <td>Wednesday</td> <td>Thursday</td> <td>Friday</td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> </div> <hr /> <p class="text-center"><input type="submit" name="btnCalculate" class="btnFormatting" value="Calculate" /></p> }
Creating a Form Collection of Web Controls
When you create a form in a view, the form is automatically equipped with a FormCollection object. Everytime you add a webcontrol to the form and give a name to that control, the control is automatically added to the form's FormCollection list. Here are examples:
@{ ViewBag.Title = "Create Employee Record"; } <h2>Create Employee Record</h2> @using (Html.BeginForm()) { <p>Employee #: @Html.TextBox("EmployeeNumber")</p> <p>First Name: @Html.TextBox("FirstName")</p> <p>Last Name: @Html.TextBox("LastName")</p> <p>Hourly Salary: @Html.TextBox("HourlySalary")</p> }
Practical Learning: Adding an Item to a Name/Value Collection
@{ ViewBag.Title = "Payroll Start-Up"; } <h2 class="text-center">Payroll Start-Up</h2> <hr /> @using (Html.BeginForm("PayrollPreparation", "Home", FormMethod.Post, new { name = "frmPayrollPreparation" })) { <div class="content"> <table> <tr> <td>Hourly Salary:</td> <td>@Html.TextBox("HourlySalary", null, new { @class = "tbxFormatting" })</td> </tr> </table> <hr /> <table> <tr> <td>Monday</td> <td>Tusday</td> <td>Wednesday</td> <td>Thursday</td> <td>Friday</td> </tr> <tr> <td>@Html.TextBox("Monday", null, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Tuesday", null, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Wednesday", null, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Thursday", null, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Friday", null, new { @class = "tbxFormatting" })</td> </tr> </table> </div> <hr /> <p class="text-center"><input type="submit" name="btnCalculate" class="btnFormatting" value="Calculate" /></p> }
Accessing the Objects of a Form Collection
To access the Web controls of a form in a controller, add a FormCollection parameter to the method action of the view.. Here is an example:
using System.Web.Mvc;
namespace Exercises.Controllers
{
public class BusinessController : Controller
{
// GET: Business
public ActionResult Index()
{
return View();
}
public ActionResult CreateEmployeeRecord(FormCollection collection)
{
return View();
}
}
}
As it was described for its parent the NameValueCollection class, the items of a FormCollection list can be accessed from one of two indexed properties. If you know the position of an item, you can pass its index to the FormCollection argument. Unlike the NameValueCollection class, if you provide an invalid index, the compiler would throw an exception. Therefore, a better or more precise way is to pass the actual name of a controller.
Practical Learning: Accessing the Form Collection Objects
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace PayrollPreparation18.Controllers { public class PayrollProcessingController : Controller { // GET: PayrollProcessing public ActionResult Index() { return View(); } // GET: PayrollProcessing/PayrollStartUp public ActionResult PayrollStartUp() { return View(); } // GET: PayrollProcessing/PayrollPreparation public ActionResult PayrollPreparation(FormCollection collection) { // Accessing FormCollection items by Name double salary = double.Parse(collection["HourlySalary"]); double monday = double.Parse(collection["Monday"]); double tuesday = double.Parse(collection["Tuesday"]); double wednesday = double.Parse(collection["Wednesday"]); double thursday = double.Parse(collection["Thursday"]); double friday = double.Parse(collection["Friday"]); double totalTime = Models.Calculations.Add5(monday, tuesday, wednesday, thursday, friday); Models.Payroll preparation = new Models.Payroll(salary, totalTime); // Accessing FormCollection items by Index ViewBag.Friday = collection[5]; ViewBag.Monday = collection[1]; ViewBag.Tuesday = collection[2]; ViewBag.Thursday = collection[4]; ViewBag.Wednesday = collection[3]; ViewBag.HourlySalary = collection[0]; ViewBag.RegularTime = preparation.RegularTime.ToString("F"); ViewBag.RegularPay = preparation.RegularPay.ToString("F"); ViewBag.Overtime = preparation.Overtime.ToString("F"); ViewBag.OvertimePay = preparation.OvertimePay.ToString("F"); ViewBag.TotalPay = preparation.NetPay.ToString("F"); collection.Add("HourlySalary", salary.ToString("F")); return View(); } } }
@{ ViewBag.Title = "Payroll Preparation"; PayrollPreparation18.Controllers.PayrollProcessingController ppc = new PayrollPreparation18.Controllers.PayrollProcessingController(); } <h2 class="text-center">Payroll Preparation</h2> <br /> @using (Html.BeginForm()) { <div class="content"> <table> <tr> <td>Hourly Salary:</td> <td>@Html.TextBox("HourlySalary", ViewBag.HourlySalary as string, new { @class = "tbxFormatting" })</td> </tr> </table> <hr /> <table> <tr> <td>Monday</td> <td>Tuesday</td> <td>Wednesday</td> <td>Thursday</td> <td>Friday</td> </tr> <tr> <td>@Html.TextBox("Monday", ViewBag.Monday as string, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Tuesday", ViewBag.Tuesday as string, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Wednesday", ViewBag.Wednesday as string, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Thursday", ViewBag.Thursday as string, new { @class = "tbxFormatting" })</td> <td>@Html.TextBox("Friday", ViewBag.Friday as string, new { @class = "tbxFormatting" })</td> </tr> </table> </div> <div class="summary"> <table> <tr> <td> </td> <td style="text-align: center">Time</td> <td style="text-align: center">Pay</td> </tr> <tr> <td>Regular:</td> <td style="text-align: center">@Html.TextBox("RegularTime", ViewBag.RegularTime as string, new { @class = "tbxFormatting" })</td> <td style="text-align: center">@Html.TextBox("RegularPay", ViewBag.RegularPay as string, new { @class = "tbxFormatting" })</td> </tr> <tr> <td>Overtime:</td> <td style="text-align: center">@Html.TextBox("Overtime", ViewBag.PayrollSummary as string, new { @class = "tbxFormatting" })</td> <td style="text-align: center">@Html.TextBox("OvertimePay", ViewBag.OvertimePay as string, new { @class = "tbxFormatting" })</td> </tr> <tr> <td> </td> <td style="text-align: center">Net Pay:</td> <td style="text-align: center">@Html.TextBox("TotalPay", ViewBag.TotalPay as string, new { @class = "tbxFormatting" })</td> </tr> </table> </div> }
Hourly Salary: 24.85 Monday: 8.00 Tuesday: 10.50 Wednesday: 8.00 Thursday: 9.50 Friday: 8.50
Introduction to Lists, Again
To use a list in your web project, you have various options. You can use an array. An array is a list where the number of items is specified in the beginning and cannot change. That is, the list cannot grow nor can it shrink. The second option is to crate a collection class. This can be a waste of time. To assist you with lists, the .NET Framework provides a rich library of collection classes.
Instead of creating your own collection class from scratch, the .NET Framework provides collection classes in the System.Collections and the System.Collections.Generic namespaces. To complement those classes, the .NET Framework provides additional classes in namespaces named System.Collections.Concurrent, System.Collections.ObjectModel, and System.Collections.Specialized. The System.Collections.Concurrent namespace contains classes for an object that is accessed by many threads at the same time. The System.Collections.Specialized namespace contains classes that are primarily used like those in the System.Collections or the System.Collections.Generic namespaces (normal/general lists, dictionaries, strings, etc) but add functionalities for particular needs.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2010-2019, FunctionX | Next |
|