Introduction to Lists
Introduction to Lists
Introduction to List-Based Classes
Overview
To support the creation of any kinds of list, the Microsoft .NET Framework provides the ArrayList and the generic List classes.The ArrayList class is defined in the System.Collections namespace while the generic List class is a member of the System.Collections.Generic namespace. The ArrayList class starts as follows:
public class ArrayList : IList, ICollection, IEnumerable, ICloneable
The generic List<T> class starts as follows:
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
Therefore, in order to use one of these classes in C# code, you can first include its namespace in the top section of the document. If you want to create an ArrayList collection in the HTML side of a webpage, you must use the class as System.Collections.ArrayList. If you want to use the List<T> class in your HTML code, simply use the name of that class.
The ArrayList class implements the IList, the ICollection, and the IEnumerable interfaces. The List class implements the generic IList<>, the generic ICollection<>, the generic IEnumerable<>, the IList, the ICollection, and the IEnumerable interfaces.
You can use either the ArrayList or the generic List class to create and manage values for a list. Here are examples of declaring variables of these classes:
@{
ViewBag.Title = "Chemistry";
}
@{
List<string> atoms = new List<string>();
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
}
Besides the ability to create a list, both the ArrayList and the List<T> classes have the built-in mechanism for serialization.
The default constructor of each class allows you to create an empty list before adding values to it. If you already have an ICollection-based list, that is, a list created from a class that implements the ICollection interface, you can initialize your ArrayList collection with it. To support this, the ArrayList class is equipped with the following constructor:
Practical Learning: Introducing Lists
body { background-color: #F7F1E8; } .nav, .navbar-header { background-color: #6E5028; } .navbar-fixed-top { background-color: #6E5028; border-bottom: 4px solid #000000; } .strong { font-weight: 600; } .jumbotron { border-radius: 18px; background-color: #ae7841; } .jumbotron > h1 { color: #f9f3ac; } .lead { text-align: justify; color: #E0D5C5; } .left-col { font-weight: 300; width: 120px; } .navbar .navbar-nav { vertical-align: top; float: none; display: inline-block; } .navbar .navbar-collapse { text-align: center; } .navbar { background-color: #6E5028; } .navbar-inverse { background-color: #6E5028; } .navbar-inverse .navbar-nav > li > a { color: #f9f3ac; } .navbar-inverse .navbar-nav > li > a:hover, .navbar-inverse .navbar-nav > li > a:focus { color: #ffffff; background: linear-gradient(#6E5028, #af8673, #6E5028); } .navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus { color: #ffffff; background-color: #523008; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Just-In-Pay</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") <link rel="stylesheet" type="text/css" href="~/Content/Utilities.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> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("JIP Home", "Index", "Home")</li> <li>@Html.ActionLink("New Employee", "CreateEmployee", "Personnel")</li> <li>@Html.ActionLink("Time Sheet", "TimeSheet", "Payroll")</li> <li>@Html.ActionLink("Payroll Start-Up", "PayrollStartUp", "Payroll")</li> <li>@Html.ActionLink("About JIP", "About", "Home")</li> <li>@Html.ActionLink("Contact Us", "Contact", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>© @DateTime.Now.Year - Just-In-Pay</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
using System; namespace JustInPay1.Models { [Serializable] public class Employee { public string EmployeeNumber { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string City { get; set; } public string County { get; set; } public string State { get; set; } public string ZIPCode { get; set; } public string MaritalStatus { get; set; } public int Exemptions { get; set; } public double HourlySalary { get; set; } public string FilingStatus { get; set; } public override bool Equals(object obj) { Employee empl = (Employee)obj; if (empl.EmployeeNumber == EmployeeNumber) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
using System; namespace JustInPay1.Models { [Serializable] public class TimeSheet { public int TimeSheetNumber { get; set; } public string EmployeeNumber { get; set; } public DateTime StartDate { get; set; } public double Week1Monday { get; set; } public double Week1Tuesday { get; set; } public double Week1Wednesday { get; set; } public double Week1Thursday { get; set; } public double Week1Friday { get; set; } public double Week1Saturday { get; set; } public double Week1Sunday { get; set; } public double Week2Monday { get; set; } public double Week2Tuesday { get; set; } public double Week2Wednesday { get; set; } public double Week2Thursday { get; set; } public double Week2Friday { get; set; } public double Week2Saturday { get; set; } public double Week2Sunday { get; set; } public override bool Equals(object obj) { TimeSheet ts = (TimeSheet)obj; if (ts.TimeSheetNumber == TimeSheetNumber) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
using System; namespace JustInPay1.Models { [Serializable] public class PayrollRecord { public int PayrollNumber { get; set; } public string EmployeeNumber { get; set; } public string EmployeeFirstName { get; set; } public string EmployeeLastName { get; set; } public string EmployeeAddress { get; set; } public string EmployeeCity { get; set; } public string EmployeeCounty { get; set; } public string EmployeeState { get; set; } public string EmployeeZIPCode { get; set; } public string EmployeeMaritalStatus { get; set; } public int EmployeeExemptions { get; set; } public double EmployeeHourlySalary { get; set; } public int EmployeeFilingStatus { get; set; } public int TimeSheetNumber { get; set; } public string TimeSheetStartDate { get; set; } public double TimeSheetWeek1Monday { get; set; } public double TimeSheetWeek1Tuesday { get; set; } public double TimeSheetWeek1Wednesday { get; set; } public double TimeSheetWeek1Thursday { get; set; } public double TimeSheetWeek1Friday { get; set; } public double TimeSheetWeek1Saturday { get; set; } public double TimeSheetWeek1Sunday { get; set; } public double TimeSheetWeek2Monday { get; set; } public double TimeSheetWeek2Tuesday { get; set; } public double TimeSheetWeek2Wednesday { get; set; } public double TimeSheetWeek2Thursday { get; set; } public double TimeSheetWeek2Friday { get; set; } public double TimeSheetWeek2Saturday { get; set; } public double TimeSheetWeek2Sunday { get; set; } public double RegularTime { get; set; } public double Overtime { get; set; } public double RegularPay { get; set; } public double OvertimePay { get; set; } public double GrossSalary { get; set; } public double TaxableGrossWagesCurrent { get; set; } public double AllowancesCurrent { get; set; } public double FederalIncomeTaxCurrent { get; set; } public double SocialSecurityTaxCurrent { get; set; } public double MedicareTaxCurrent { get; set; } public double StateIncomeTaxCurrent { get; set; } public double TaxableGrossWagesYTD { get; set; } public double AllowancesYTD { get; set; } public double FederalIncomeTaxYTD { get; set; } public double SocialSecurityTaxYTD { get; set; } public double MedicareTaxYTD { get; set; } public double StateIncomeTaxYTD { get; set; } public override bool Equals(object obj) { PayrollRecord pr = (PayrollRecord)obj; if (pr.PayrollNumber == PayrollNumber) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
namespace JustInPay1.Models { public class WorkDay { public WorkDay(double time, double salary) { HourSalary = salary; TimeWorked = time; } public double HourSalary { get; set; } public double TimeWorked { get; set; } public double OvertimeRate => HourSalary * 1.50; public double RegularTime { get { if (TimeWorked <= 8.00) return TimeWorked; else return 8.00; } } public double Overtime { get { if (TimeWorked <= 8.00) return 0.00; else return TimeWorked - 8.00; } } public double RegularPay => RegularTime * HourSalary; public double OvertimePay => OvertimeRate * Overtime; public double NetPay => RegularPay + OvertimePay; } }
@{ ViewBag.Title = "JIP Home"; } <div class="jumbotron"> <h1>Just-In-Pay</h1> <p class="lead">Just-In-Pay is a private company that creates and manages time sheets (or time cards) on behalf of all types of entities, including individuals, small businesses, enterprises, as well as government agencies. We also create, process, manage, and maintain payroll for our clients. We spare the hasle of tax laws and related regulations so our clients can concentrate on their most important jobs: taking care of their employees and delivering the best services and products they can to their customers.</p> <p><a href="https://asp.net" class="btn btn-warning btn-lg text-right">Learn more »</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Our Services</h2> <p>Get to know our time sheet dissemination, online publications, and ease of use. This introductory section provides clear and detailed information about our processes.</p> <p><a class="btn btn-warning text-right" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p> </div> <div class="col-md-4"> <h2>Online Outreach</h2> <p>Our smooth online services allow employees and client to access and manage their time sheets from any device. We the highest and most demanding standards of online services.</p> <p><a class="btn btn-warning text-right" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p> </div> <div class="col-md-4"> <h2>Payroll Intricacies</h2> <p>With our payroll services, you will no longer be burdened with legislative details and law small print. Our knowledgeable employees, certified accountant, tax lawyers are the best.</p> <p><a class="btn btn-warning text-right" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p> </div> </div>
The Capacity of a List
After declaring an ArrayList or a List<T> variable, it is empty. As objects are added to it, the list grows. The list can grow tremendously as you wish. The number of items of the list is managed through the memory it occupies and this memory grows as needed. The number of items that the memory allocated is currently using is represented by the Capacity property:
ArrayList: public virtual int Capacity { get; set; } List<T>: public int Capacity { get; set; }
The capacity of a list will usually be the least of your concerns. If for some reason, you want to intervene and control the number of items that your list can contain, you can manipulate the Capacity property. For example, you can assign it a constant to set the maximum value that the list can contain. Instead of specifying the capacity after the list has been created, when declaring the list variable, you can specify its maximum capacity. To support this, both the ArrayList and the List classes are equipped with an additional constructor as follows:
public ArrayList(int capacity); public List(int capacity);
You will hardly have any reason to use the Capacity property:
The Number of Items in a Collection
To provide the number of items in a collection, both the ArrayList and the List classes are equipped with a property named Count, which is an integer.
The Capacity and the Count properties have this in common: the value of each increases as the list grows and the same value decreases if the list shrinks. On the other hand, Capacity is a read/write property. This means that you can assign a value to the capacity to fix the number of items that the list can contain. You can also get the value of the Capacity. The Count property is read-only because the counting of the current number of items is performed without your intervention.
A Read-Only List
A collection is said to be read-only if it doesn't allow the addition of items. To let you produce a read-only collection, the ArrayList provides an overloaded method named ReadOnly. The syntaxes of the two versions are:
public static ArrayList ReadOnly(ArrayList list) public static IList ReadOnly(IList list)
Some operations cannot be performed on a read-only list. To perform such operations, you can first find out whether an ArrayList list is read-only. This is done by checking its IsReadOnly property.
Adding Values or Objects to a Collection
Adding an Item
The primary operation performed on a list is to add a value or an object to it. To support this, both the ArrayList and the List classes are equipped with an Add() method. The syntax of the System.Collections.ArrayList.Add() method is:
public virtual int Add(object value);
The syntax of the System.Collections.Generic.List.Add() method is:
public void Add(T value);
The argument of the method is the value or object to add to the collection. If the method succeeds with the addition, it returns the position where the value or object was added in the list. Here are example for an ArrayList variable:
@{
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
molecules.Add("Ozone");
molecules.Add("Oxygen");
molecules.Add("Helium");
molecules.Add("Sulfuric Acid");
molecules.Add("Carbon Dioxide");
}
If the method fails to add the value and if you are using an ArrayList class, the compiler would throw an exception. The error could result from the list being read-only or being full.
Practical Learning: Adding an Item to a Collection
using System; using System.IO; using System.Web.Mvc; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace JustInPay1.Controllers { public class PersonnelController : Controller { // GET: Personnel public ActionResult Index() { return View(); } // GET: Personnel/CreateEmployee public ActionResult CreateEmployee() { return View(); } // GET: Personnel/SaveEmployeeRecord public ActionResult SaveEmployeeRecord(string EmployeeNumber, string FirstName, string LastName, string Address, string City, string County, string State, string ZIPCode, string MaritalStatus, int Exemptions, double HourlySalary, string FilingStatus) { FileStream fsEmployees = null; BinaryFormatter bfEmployees = new BinaryFormatter(); List<Models.Employee> employees = new List<Models.Employee>(); string strEmployeesFile = Server.MapPath("~/App_Data/Employees.mpl"); // In order to create an Employee object, make sure the user provides at least an employee number. if (!string.IsNullOrEmpty("EmployeeNumber")) { // If a file for employees records was proviously created, open it if (System.IO.File.Exists(strEmployeesFile)) { using (fsEmployees = new FileStream(strEmployeesFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { /* After opening the file, get the list of records from it * and store in the empty List<> collection we started. */ employees = (List<Models.Employee>)bfEmployees.Deserialize(fsEmployees); } } // Create an Employee object using the data from the form Models.Employee empl = new Models.Employee() { EmployeeNumber = EmployeeNumber, FirstName = FirstName, LastName = LastName, Address = Address, City = City, County = County, State = State, ZIPCode = ZIPCode, MaritalStatus = MaritalStatus, Exemptions = Convert.ToInt32(Exemptions), HourlySalary = Convert.ToDouble(HourlySalary), FilingStatus = FilingStatus }; // Add the new employee to the existing list of employees employees.Add(empl); // Save the list of employees in the appropriate file using (fsEmployees = new FileStream(strEmployeesFile, FileMode.Create, FileAccess.Write, FileShare.Write)) { bfEmployees.Serialize(fsEmployees, employees); } // If the list of employeees has been created/updated and saved, take the user back to the form. return RedirectToAction("CreateEmployee"); } return View(); } } }
@{ ViewBag.Title = "New Employee Record"; } <h2 class="text-center">New Employee Record</h2> <div class="tbl-empl"> @using (Html.BeginForm("SaveEmployeeRecord", "Personnel", FormMethod.Post)) { <table> <tr> <td class="left-col">Employee #:</td> <td>@Html.TextBox("EmployeeNumber", "", new { style = "width: 100px" })</td> <td style="width: 100px"> </td> <td> </td> </tr> <tr> <td>First Name:</td> <td>@Html.TextBox("FirstName", "", new { style = "width: 100px" })</td> <td>Last Name:</td> <td>@Html.TextBox("LastName", "", new { style = "width: 100px" })</td> </tr> <tr> <td>Address:</td> <td colspan="3">@Html.TextBox("Address", "", new { style = "width: 400px" })</td> </tr> <tr> <td>City:</td> <td>@Html.TextBox("City", "", new { style = "width: 100px" })</td> <td>County:</td> <td>@Html.TextBox("County", "", new { style = "width: 100px" })</td> </tr> <tr> <td>State:</td> <td>@Html.TextBox("State", "", new { style = "width: 100px" })</td> <td>ZIP-Code:</td> <td>@Html.TextBox("ZIPCode", "", new { style = "width: 100px" })</td> </tr> <tr> <td>Hourly Salary:</td> <td>@Html.TextBox("HourlySalary", "", new { style = "width: 100px" })</td> <td>Marital Status:</td> <td> <select name="MaritalStatus"> <option value="Unknown">Unknown</option> <option value="Single">Single</option> <option value="Married">Married</option> </select> </td> </tr> <tr> <td>Exemptions:</td> <td>@Html.TextBox("Exemptions", "", new { style = "width: 100px" })</td> <td>Filing Status:</td> <td> <select name="FilingStatus"> <option value="Unknown">Unknown</option> <option value="HeadOfHousehold">Head of Household</option> <option value="MarriedFilingJointly">Married Filing Jointly</option> </select> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td><input type="submit" name="btnSubmit" value="Submit" style="width: 120px" /></td> </tr> </table> } </div>
1 | 2 | 3 | 4 | |
Employee # | 941148 | 927048 | 606384 | 952748 |
First Name | Catherine | Henry | Herbert | David |
Last Name | Watts | Meuer | Gibson | Evans |
Address | 12004 Harrington Ave | 802 Wheeler Street | 10324 Marina Ave | 5102 Piedmont Rd |
City | Baltimore | York | College Park | Silver Spring |
County | Baltimore | York | Prince George | Montgomery |
State | MD | PA | MD | MD |
ZIP Code | 21206 | 17401 | 20742 | 20910 |
Marital Status | Single |
|
|
Single |
Exemptions | 0 | 3 | 1 | 2 |
Hourly Salary | 26.15 | 12.95 | 22.25 | 17.25 |
Filing Status | Head of Household | Head of Household | Head of Household | Head of Household |
Adding a Range of Items
Instead of adding one value at a time, you can first create a list of values and add that whole list at once. To support this operation, both the ArrayList and the List classes are equipped with a method named AddRange.
The syntax of the ArrayList.AddRange() method is:
public virtual void AddRange(ICollection collection);
The syntax of the List<>.AddRange() method is:
public void AddRange(IEnumerable<T> collection);
The ArrayList.AddRange() method takes as argument a list created from a class that implements the ICollection interface. The List<>.AddRange() method takes as argument a list created from a class that implements the generic IEnumerable interface. Here is an example:
using System.Collections.Generic; using System.IO; using System.Web.Mvc; using System.Runtime.Serialization.Formatters.Binary; namespace JustInPay1.Controllers { public class HomeController : Controller { public ActionResult Index() { List<TimeSheet> timeSheets = new List<TimeSheet>(); BinaryFormatter bfTimeSheets = new BinaryFormatter(); string strFileTimeSheets = Server.MapPath("~/App_Data/TimeSheets.tss"); List<TimeSheet> totalWork = new List<TimeSheet>(); totalWork.Add(new TimeSheet() { TimeSheetNumber = 100001, EmployeeNumber = "606384", StartDate = new DateTime(2018, 1, 1), Week1Monday = 0, Week1Tuesday = 0, Week1Wednesday = 0.00, Week1Thursday = 0.00, Week1Friday = 0.00, Week1Saturday = 8, Week1Sunday = 8, Week2Monday = 0.00, Week2Tuesday = 0, Week2Wednesday = 0.00, Week2Thursday = 0, Week2Friday = 0, Week2Saturday = 8, Week2Sunday = 8.00 }); totalWork.Add(new TimeSheet() { TimeSheetNumber = 100002, EmployeeNumber = "952748", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); totalWork.Add(new TimeSheet() { TimeSheetNumber = 100003, EmployeeNumber = "941148", StartDate = new DateTime(2018, 1, 1), Week1Monday = 9, Week1Tuesday = 10, Week1Wednesday = 8.50, Week1Thursday = 9.50, Week1Friday = 10.50, Week1Saturday = 12, Week1Sunday = 12, Week2Monday = 8.50, Week2Tuesday = 9, Week2Wednesday = 9.50, Week2Thursday = 8, Week2Friday = 10, Week2Saturday = 10, Week2Sunday = 8.50 }); totalWork.Add(new TimeSheet() { TimeSheetNumber = 100004, EmployeeNumber = "927048", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); timeSheets.AddRange(totalWork); using (FileStream fsTimeSheets = new FileStream(strFileTimeSheets, FileMode.Create, FileAccess.Write, FileShare.Write)) { bfTimeSheets.Serialize(fsTimeSheets, timeSheets); } return View(); } } }
Practical Learning: Adding a Range of Items
using System; using System.IO; using System.Web; using System.Web.Mvc; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace JustInPay1.Controllers { public class PayrollController : Controller { // GET: Payroll public ActionResult Index() { List<Models.TimeSheet> timeSheets = new List<Models.TimeSheet>(); BinaryFormatter bfTimeSheets = new BinaryFormatter(); string strTimeSheetsFile = Server.MapPath("~/App_Data/TimeSheets.tss"); List<Models.TimeSheet> totalWork = new List<Models.TimeSheet>(); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100001, EmployeeNumber = "606384", StartDate = new DateTime(2018, 1, 1), Week1Monday = 0, Week1Tuesday = 0, Week1Wednesday = 0.00, Week1Thursday = 0.00, Week1Friday = 0.00, Week1Saturday = 8, Week1Sunday = 8, Week2Monday = 0.00, Week2Tuesday = 0, Week2Wednesday = 0.00, Week2Thursday = 0, Week2Friday = 0, Week2Saturday = 8, Week2Sunday = 8.00 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100002, EmployeeNumber = "952748", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100003, EmployeeNumber = "941148", StartDate = new DateTime(2018, 1, 1), Week1Monday = 9, Week1Tuesday = 10, Week1Wednesday = 8.50, Week1Thursday = 9.50, Week1Friday = 10.50, Week1Saturday = 12, Week1Sunday = 12, Week2Monday = 8.50, Week2Tuesday = 9, Week2Wednesday = 9.50, Week2Thursday = 8, Week2Friday = 10, Week2Saturday = 10, Week2Sunday = 8.50 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100004, EmployeeNumber = "927048", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); timeSheets.AddRange(totalWork); using (FileStream fsTimeSheets = new FileStream(strTimeSheetsFile, FileMode.Create, FileAccess.Write, FileShare.Write)) { bfTimeSheets.Serialize(fsTimeSheets, timeSheets); } return View(); } } }
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
namespace JustInPay1.Controllers
{
public class PayrollController : Controller
{
// GET: Payroll
public ActionResult Index()
{
List<Models.TimeSheet> timeSheets = new List<Models.TimeSheet>();
BinaryFormatter bfTimeSheets = new BinaryFormatter();
string strTimeSheetsFile = Server.MapPath("~/App_Data/TimeSheets.tss");
List<Models.TimeSheet> totalWork = new List<Models.TimeSheet>();
totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100001, EmployeeNumber = "606384", StartDate = new DateTime(2018, 1, 1), Week1Monday = 0, Week1Tuesday = 0, Week1Wednesday = 0.00, Week1Thursday = 0.00, Week1Friday = 0.00, Week1Saturday = 8, Week1Sunday = 8, Week2Monday = 0.00, Week2Tuesday = 0, Week2Wednesday = 0.00, Week2Thursday = 0, Week2Friday = 0, Week2Saturday = 8, Week2Sunday = 8.00 });
totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100002, EmployeeNumber = "952748", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 });
totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100003, EmployeeNumber = "941148", StartDate = new DateTime(2018, 1, 1), Week1Monday = 9, Week1Tuesday = 10, Week1Wednesday = 8.50, Week1Thursday = 9.50, Week1Friday = 10.50, Week1Saturday = 12, Week1Sunday = 12, Week2Monday = 8.50, Week2Tuesday = 9, Week2Wednesday = 9.50, Week2Thursday = 8, Week2Friday = 10, Week2Saturday = 10, Week2Sunday = 8.50 });
totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100004, EmployeeNumber = "927048", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 });
timeSheets.AddRange(totalWork);
/* using (FileStream fsTimeSheets = new FileStream(strTimeSheetsFile, FileMode.Create, FileAccess.Write, FileShare.Write))
{
bfTimeSheets.Serialize(fsTimeSheets, timeSheets);
} */
return View();
}
}
}
Getting a Value or Object from a Collection
Introduction
A computer language like C# has built-in means to look for an item in a collection. This can be done by first using a loop to visit each member of a collection, then using a conditional statement to check the value of an item or compare it to a condition.
Getting to an Item Using an Indexer
To give you access to each member of their list, both the ArrayList and the List classes are equipped with the default Item property. The Item property is an indexer. The first value of the list has an index of 0. The second has an index of 1, and so on.
To get a single value based on its position, you can apply the square brackets of arrays to the variable. Here is an example:
@{
ViewBag.Title = "Chemistry";
}
@{
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
molecules.Add("Ozone");
molecules.Add("Oxygen");
molecules.Add("Helium");
molecules.Add("Sulfuric Acid");
molecules.Add("Carbon Dioxide");
}
<p>Molecule: @molecules[1]</p>
Based on this, you can use a loop (while, do...while, or for) to visit each item through its index.
An issue to keep in mind is that the ArrayList[] indexer returns an Object value. Therefore, you may have to cast this value to your type of value to get it right.
Iterating Through a Collection
Besides using the index to access a value from the list, the ArrayList and the List classes implement the IEnumerable.GetEnumerator() method. For this reason, you can use the foreach loop to access each member of the collection. Here is an example:
@{ ViewBag.Title = "Chemistry"; } @{ System.Collections.ArrayList molecules = new System.Collections.ArrayList(); molecules.Add("Ozone"); molecules.Add("Oxygen"); molecules.Add("Helium"); molecules.Add("Sulfuric Acid"); molecules.Add("Carbon Dioxide"); } <ul> @foreach (string molecule in molecules) { <li>@molecule</li> } </ul>
You can use the Item property to change a value in the list. Because the Item property is used to access an existing value from the list, the value must have been created. If you try setting the value of a non-existing item, the compiler would throw an ArgumentOutOfRangeException Exception.
Taking Action For Each Value or Object
To provide you a faster means of accessing each item in a collection, the List class is equipped with a method named ForEach. Its syntax is:
public void ForEach(Action<T> action);
This method takes an Action delegate as argument.
Checking Whether a List Contains an Item
Instead of the square brackets that allow you to retrieve a value based on its position, you can look for a value based on its complete definition. You have various options. You can first "build" an item and ask the compiler to check whether any item in the list matches your definition. To perform this search, depending on your class, you can call either the ArrayList.Contains() or the List.Contains() method. The syntax of the System.Collections.ArrayList.Contains() method is:
public virtual bool Contains(object value);
The syntax of the System.Collections.Generic.List.Contains() method is:
public bool Contains(T value);
The value to look for is passed as argument to the method. The compiler would look for the value or object, using the value type or the object definition. If the argument corresponds to an existing value or object, the method returns true. If the value or object is not found, the method returns false. Here is an example:
@{ ViewBag.Title = "Chemistry"; } @{ System.Collections.ArrayList molecules = new System.Collections.ArrayList(); molecules.Add("Ozone"); molecules.Add("Oxygen"); molecules.Add("Helium"); molecules.Add("Sulfuric Acid"); molecules.Add("Carbon Dioxide"); } <p>Oxygen is in the list: @molecules.Contains("Oxygen")</p> <p>Oxygène is in the list: @molecules.Contains("Oxygène")</p>
Searching for an Item
Another option to look for an item in a list consists of calling a method named BinarySearch supported by both the ArrayList and the List class. It is overloaded in three versions and one of them uses the following syntax:
public virtual int BinarySearch(object value); public int BinarySearch(T value);
The value to look for is passed as argument to the method. Here is an example:
private void btnResult_Click(object sender, EventArgs e) { string strFind = txtFind.Text; if( lstNames.BinarySearch(strFind) > 0 ) txtResult.Text = "Found"; else txtResult.Text = "Not Found"; }
Checking the Existence of an Item
To let you check whether a certain item exists in a collection, the list classes contains a method named Exists. Its syntax is:
public bool Exists(Predicate<T> match);
This method takes a delegate as argument. Here is an example
@{
ViewBag.Title = "Existense";
}
<h2>Existense</h2>
@{
string strMessage = string.Empty;
string strEmployeeNumber = string.Empty;
FileStream fsEmployees = null;
string strFileEmployees = Server.MapPath("~/App_Data/Employees.mpl");
List<FunDepartmentStore1.App_Code.Employee> employees = new List<FunDepartmentStore1.App_Code.Employee>();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bfEmployees = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
if (IsPost)
{
strEmployeeNumber = Request["txtEmployeeNumber"];
if (File.Exists(strFileEmployees))
{
using (fsEmployees = new FileStream(strFileEmployees, FileMode.Open, FileAccess.Read, FileShare.Read))
{
employees = (List<FunDepartmentStore1.App_Code.Employee>)bfEmployees.Deserialize(fsEmployees);
bool exists = employees.Exists((FunDepartmentStore1.App_Code.Employee member) =>
{
return member.EmployeeNumber == strEmployeeNumber;
});
if (exists == true)
{
strMessage = "The database contains an employee with that number.";
}
else
{
strMessage = "Our database doesn't have an employee with such a number.";
}
}
}
}
}
@using (Html.BeginForm())
{
<table>
<tr>
<td style="width: 120px"><b>Employee #:</b></td>
<td>@Html.TextBox("txtEmployeeNumber", @strEmployeeNumber, new { style = "width: 100px" })</td>
<td style="width: 100px"><input type="submit" name="btnFind" value="Find" style="width: 80px" /></td>
<td> </td>
</tr>
</table>
<p>@strMessage</p>
}
Finding a Value or Object in a Collection
To let you find an item in a collection, the List class is equipped with a method named Find. Its syntax is:
public T Find(Predicate<T> match);
This method takes a delegate as argument.
Practical Learning: Finding a Value or Object in a List
using System; using System.IO; using System.Web.Mvc; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; namespace PayrollProcessing2.Controllers { public class PayrollController : Controller { // GET: Payroll public ActionResult Index() { List<Models.TimeSheet> timeSheets = new List<Models.TimeSheet>(); BinaryFormatter bfTimeSheets = new BinaryFormatter(); string strTimeSheetsFile = Server.MapPath("~/App_Data/TimeSheets.tss"); List<Models.TimeSheet> totalWork = new List<Models.TimeSheet>(); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100001, EmployeeNumber = "606384", StartDate = new DateTime(2018, 1, 1), Week1Monday = 0, Week1Tuesday = 0, Week1Wednesday = 0.00, Week1Thursday = 0.00, Week1Friday = 0.00, Week1Saturday = 8, Week1Sunday = 8, Week2Monday = 0.00, Week2Tuesday = 0, Week2Wednesday = 0.00, Week2Thursday = 0, Week2Friday = 0, Week2Saturday = 8, Week2Sunday = 8.00 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100002, EmployeeNumber = "952748", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100003, EmployeeNumber = "941148", StartDate = new DateTime(2018, 1, 1), Week1Monday = 9, Week1Tuesday = 10, Week1Wednesday = 8.50, Week1Thursday = 9.50, Week1Friday = 10.50, Week1Saturday = 12, Week1Sunday = 12, Week2Monday = 8.50, Week2Tuesday = 9, Week2Wednesday = 9.50, Week2Thursday = 8, Week2Friday = 10, Week2Saturday = 10, Week2Sunday = 8.50 }); totalWork.Add(new Models.TimeSheet() { TimeSheetNumber = 100004, EmployeeNumber = "927048", StartDate = new DateTime(2018, 1, 1), Week1Monday = 8, Week1Tuesday = 8, Week1Wednesday = 8.00, Week1Thursday = 8.00, Week1Friday = 8.00, Week1Saturday = 0, Week1Sunday = 0, Week2Monday = 8.00, Week2Tuesday = 8, Week2Wednesday = 8.00, Week2Thursday = 8, Week2Friday = 8, Week2Saturday = 0, Week2Sunday = 0.00 }); timeSheets.AddRange(totalWork); /* using (FileStream fsTimeSheets = new FileStream(strTimeSheetsFile, FileMode.Create, FileAccess.Write, FileShare.Write)) { bfTimeSheets.Serialize(fsTimeSheets, timeSheets); } */ return View(); } // GET: Payroll/PayrollStartUp public ActionResult PayrollStartUp() { return View(); } // GET: Payroll/PayrollPreparation public ActionResult PayrollPreparation(string TimeSheetNumber) { if (string.IsNullOrEmpty(TimeSheetNumber)) { ViewBag.ErrorMessage = "Invalid Time Sheet Number"; } else { string strEmployeeNumber = string.Empty; List<Models.Employee> employees = new List<Models.Employee>(); int iTimeSheetNumber = int.Parse(TimeSheetNumber); List<Models.TimeSheet> timeSheets = new List<Models.TimeSheet>(); BinaryFormatter bfEmployees = new BinaryFormatter(); BinaryFormatter bfTimeSheets = new BinaryFormatter(); string strFileEmployees = Server.MapPath("~/App_Data/Employees.mpl"); string strFileTimeSheets = Server.MapPath("~/App_Data/TimeSheets.tss"); using (FileStream fsTimeSheets = new FileStream(strFileTimeSheets, FileMode.Open, FileAccess.Read, FileShare.Read)) { timeSheets = (List<Models.TimeSheet>)bfTimeSheets.Deserialize(fsTimeSheets); Models.TimeSheet timeWorked = timeSheets.Find((Models.TimeSheet ts) => { return ts.TimeSheetNumber == iTimeSheetNumber; }); if (timeWorked != null) { ViewBag.TimeSheet = timeWorked; strEmployeeNumber = timeWorked.EmployeeNumber; } else { ViewBag.ErrorMessage = "Our database doesn't have a time sheet with that number."; } } using (FileStream fsEmployees = new FileStream(strFileEmployees, FileMode.Open, FileAccess.Read, FileShare.Read)) { employees = (List<Models.Employee>)bfEmployees.Deserialize(fsEmployees); Models.Employee staff = employees.Find((Models.Employee empl) => { return empl.EmployeeNumber == strEmployeeNumber; }); if (staff != null) { ViewBag.Employee = staff; } else { ViewBag.ErrorMessage = "Our database doesn't have an employee with such a number."; } } } return View(); } } }
@{ ViewBag.Title = "Payroll Preparation"; } <h2>Payroll Preparation</h2> @{ string strCity = string.Empty; string strState = string.Empty; string strCounty = string.Empty; string strZIPCode = string.Empty; string strAddress = string.Empty; string strMessage = string.Empty; string strLastName = string.Empty; string strFirstName = string.Empty; string strFilingStatus = string.Empty; string strMaritalStatus = string.Empty; string strEmployeeNumber = string.Empty; PayrollProcessing2.Models.TimeSheet timeSheet = ViewBag.TimeSheet; PayrollProcessing2.Models.Employee employee = ViewBag.Employee; PayrollProcessing2.Models.PayrollRecord payEval = new PayrollProcessing2.Models.PayrollRecord(); DateTime dtStartDate = timeSheet.StartDate; DateTime dtEndDate = dtStartDate.AddDays(13); int timeSheetNumber = timeSheet.TimeSheetNumber; string strWeek1Monday = dtStartDate.ToShortDateString(); string strWeek1Tuesday = dtStartDate.AddDays(1).ToShortDateString(); string strWeek1Wednesday = dtStartDate.AddDays(2).ToShortDateString(); string strWeek1Thursday = dtStartDate.AddDays(3).ToShortDateString(); string strWeek1Friday = dtStartDate.AddDays(4).ToShortDateString(); string strWeek1Saturday = dtStartDate.AddDays(5).ToShortDateString(); string strWeek1Sunday = dtStartDate.AddDays(6).ToShortDateString(); string strWeek2Monday = dtStartDate.AddDays(7).ToShortDateString(); string strWeek2Tuesday = dtStartDate.AddDays(8).ToShortDateString(); string strWeek2Wednesday = dtStartDate.AddDays(9).ToShortDateString(); string strWeek2Thursday = dtStartDate.AddDays(10).ToShortDateString(); string strWeek2Friday = dtStartDate.AddDays(11).ToShortDateString(); string strWeek2Saturday = dtStartDate.AddDays(12).ToShortDateString(); string strWeek2Sunday = dtStartDate.AddDays(13).ToShortDateString(); PayrollProcessing2.Models.WorkDay wdWeek1Monday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Monday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Tuesday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Tuesday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Wednesday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Wednesday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Thursday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Thursday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Friday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Friday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Saturday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Saturday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek1Sunday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week1Sunday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Monday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Monday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Tuesday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Tuesday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Wednesday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Wednesday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Thursday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Thursday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Friday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Friday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Saturday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Saturday, employee.HourlySalary); PayrollProcessing2.Models.WorkDay wdWeek2Sunday = new PayrollProcessing2.Models.WorkDay(timeSheet.Week2Sunday, employee.HourlySalary); } @using (Html.BeginForm()) { <table style="width: 785px"> <tr style="background-color: #443018; color: #DDDBB2; border-bottom: 1px solid #ffd800; border-top: 1px solid #ffd800"> <td style="width: 160px; font-weight: 600">Time Sheet #:</td> <td><b>@timeSheet.TimeSheetNumber</b></td> </tr> </table> <table style="width: 785px"> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 160px; font-weight: 600">Time Sheet Start Date:</td> <td style="width: 100px">@dtStartDate.ToShortDateString()</td> <td style="width: 100px; font-weight: bold">End Date:</td> <td>@dtEndDate.ToShortDateString()</td> </tr> </table> <table style="width: 785px"> <tr> <td style="width: 160px; font-weight: 600">Employee:</td> <td style="width: 100px">@employee.EmployeeNumber</td> <td style="width: 100px">@employee.FirstName</td> <td>@employee.LastName</td> </tr> </table> <table style="width: 785px"> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 160px; font-weight: 600">Address:</td> <td style="width: 200px">@employee.Address</td> <td style="width: 100px; font-weight: 600">City:</td> <td>@employee.City</td> </tr> </table> <table style="width: 785px"> <tr> <td style="width: 160px; font-weight: 600">County:</td> <td>@employee.County</td> <td style="width: 160px; font-weight: 600; text-align: center">State:</td> <td>@employee.State</td> <td style="text-align: center; font-weight: 600;">ZIP-Code:</td> <td>@employee.ZIPCode</td> </tr> </table> <table style="width: 785px"> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 160px; font-weight: 600">Marital Status:</td> <td>@employee.MaritalStatus</td> <td> </td> <td><b>Exemptions:</b></td> <td>@employee.Exemptions</td> <td><b>Hourly Salary:</b></td> <td>@employee.HourlySalary</td> <td><b>Filing Status:</b></td> <td>@employee.FilingStatus</td> </tr> </table> <hr /> <table> <tr style="background-color: #443018; color: #DDDBB2"> <td style="width: 160px"> </td> <td style="width: 90px; font-weight: 600">Monday</td> <td style="width: 90px; font-weight: 600">Tuesday</td> <td style="width: 90px; font-weight: 600">Wednesday</td> <td style="width: 90px; font-weight: 600">Thursday</td> <td style="width: 90px; font-weight: 600">Friday</td> <td style="width: 90px; font-weight: 600">Saturday</td> <td style="width: 90px; font-weight: 600">Sunday</td> </tr> <tr style="background-color: #6E5028; color: #DDDBB2; border-bottom: 1px solid #ffd800; border-top: 1px solid #ffd800"> <td> </td> <td>@strWeek1Monday</td> <td>@strWeek1Tuesday</td> <td>@strWeek1Wednesday</td> <td>@strWeek1Thursday</td> <td>@strWeek1Friday</td> <td>@strWeek1Saturday</td> <td>@strWeek1Sunday</td> </tr> <tr style="background-color: #C09052; color: #000000; border-bottom: 1px solid #ffd800"> <td style="width: 120px; font-weight: bold">Week 1</td> <td>@timeSheet.Week1Monday.ToString("F")</td> <td>@timeSheet.Week1Tuesday.ToString("F")</td> <td>@timeSheet.Week1Wednesday.ToString("F"))</td> <td>@timeSheet.Week1Thursday.ToString("F")</td> <td>@timeSheet.Week1Friday.ToString("F")</td> <td>@timeSheet.Week1Saturday.ToString("F")</td> <td>@timeSheet.Week1Sunday.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="font-weight: bold">Regular Time</td> <td>@wdWeek1Monday.RegularTime.ToString("F")</td> <td>@wdWeek1Tuesday.RegularTime.ToString("F")</td> <td>@wdWeek1Wednesday.RegularTime.ToString("F")</td> <td>@wdWeek1Thursday.RegularTime.ToString("F")</td> <td>@wdWeek1Friday.RegularTime.ToString("F")</td> <td>@wdWeek1Saturday.RegularTime.ToString("F")</td> <td>@wdWeek1Sunday.RegularTime.ToString("F")</td> </tr> <tr> <td style="width: 120px; font-weight: bold; ">Overtime</td> <td>@wdWeek1Monday.Overtime.ToString("F")</td> <td>@wdWeek1Tuesday.Overtime.ToString("F")</td> <td>@wdWeek1Wednesday.Overtime.ToString("F")</td> <td>@wdWeek1Thursday.Overtime.ToString("F")</td> <td>@wdWeek1Friday.Overtime.ToString("F")</td> <td>@wdWeek1Saturday.Overtime.ToString("F")</td> <td>@wdWeek1Sunday.Overtime.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 120px; font-weight: bold;">Regular Pay</td> <td>@wdWeek1Monday.RegularPay.ToString("F")</td> <td>@wdWeek1Tuesday.RegularPay.ToString("F")</td> <td>@wdWeek1Wednesday.RegularPay.ToString("F")</td> <td>@wdWeek1Thursday.RegularPay.ToString("F")</td> <td>@wdWeek1Friday.RegularPay.ToString("F")</td> <td>@wdWeek1Saturday.RegularPay.ToString("F"))</td> <td>@wdWeek1Sunday.RegularPay.ToString("F")</td> </tr> <tr> <td style="width: 120px; font-weight: bold">Overtime Pay</td> <td>@wdWeek1Tuesday.OvertimePay.ToString("F")</td> <td>@wdWeek1Wednesday.OvertimePay.ToString("F")</td> <td>@wdWeek1Thursday.OvertimePay.ToString("F")</td> <td>@wdWeek1Friday.OvertimePay.ToString("F")</td> <td>@wdWeek1Saturday.OvertimePay.ToString("F")</td> <td>@wdWeek1Sunday.OvertimePay.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 120px; font-weight: bold">Net Pay</td> <td>@wdWeek1Monday.NetPay.ToString("F")</td> <td>@wdWeek1Tuesday.NetPay.ToString("F")</td> <td>@wdWeek1Wednesday.NetPay.ToString("F")</td> <td>@wdWeek1Thursday.NetPay.ToString("F")</td> <td>@wdWeek1Friday.NetPay.ToString("F")</td> <td>@wdWeek1Saturday.NetPay.ToString("F")</td> <td>@wdWeek1Sunday.NetPay.ToString("F")</td> </tr> </table> <hr /> <table> <tr style="background-color: #6E5028; color: #DDDBB2; border-bottom: 1px solid #ffd800; border-top: 1px solid #ffd800"> <td> </td> <td>@strWeek2Monday</td> <td>@strWeek2Tuesday</td> <td>@strWeek2Wednesday</td> <td>@strWeek2Thursday</td> <td>@strWeek2Friday</td> <td>@strWeek2Saturday</td> <td>@strWeek2Sunday</td> </tr> <tr style="background-color: #C09052; color: #000000; border-bottom: 1px solid #ffd800"> <td style="width: 160px; font-weight: bold">Week 2</td> <td style="width: 90px">@timeSheet.Week2Monday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Tuesday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Wednesday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Thursday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Friday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Saturday.ToString("F")</td> <td style="width: 90px">@timeSheet.Week2Sunday.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 120px; font-weight: bold">Regular Time</td> <td>@wdWeek2Monday.RegularTime.ToString("F")</td> <td>@wdWeek2Tuesday.RegularTime.ToString("F")</td> <td>@wdWeek2Wednesday.RegularTime.ToString("F")</td> <td>@wdWeek2Thursday.RegularTime.ToString("F")</td> <td>@wdWeek2Friday.RegularTime.ToString("F")</td> <td>@wdWeek2Saturday.RegularTime.ToString("F")</td> <td>@wdWeek2Sunday.RegularTime.ToString("F")</td> </tr> <tr> <td style="width: 120px; font-weight: bold">Overtime</td> <td>@wdWeek2Monday.Overtime.ToString("F")</td> <td>@wdWeek2Tuesday.Overtime.ToString("F")</td> <td>@wdWeek2Wednesday.Overtime.ToString("F")</td> <td>@wdWeek2Thursday.Overtime.ToString("F")</td> <td>@wdWeek2Friday.Overtime.ToString("F")</td> <td>@wdWeek2Saturday.Overtime.ToString("F")</td> <td>@wdWeek2Sunday.Overtime.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 120px; font-weight: bold">Regular Pay</td> <td>@wdWeek2Monday.RegularPay.ToString("F")</td> <td>@wdWeek2Tuesday.RegularPay.ToString("F")</td> <td>@wdWeek2Wednesday.RegularPay.ToString("F")</td> <td>@wdWeek2Thursday.RegularPay.ToString("F")</td> <td>@wdWeek2Friday.RegularPay.ToString("F")</td> <td>@wdWeek2Saturday.RegularPay.ToString("F")</td> <td>@wdWeek2Sunday.RegularPay.ToString("F")</td> </tr> <tr> <td style="width: 120px; font-weight: bold">Overtime Pay</td> <td>@wdWeek2Monday.OvertimePay.ToString("F")</td> <td>@wdWeek2Tuesday.OvertimePay.ToString("F")</td> <td>@wdWeek2Wednesday.OvertimePay.ToString("F")</td> <td>@wdWeek2Thursday.OvertimePay.ToString("F")</td> <td>@wdWeek2Friday.OvertimePay.ToString("F")</td> <td>@wdWeek2Saturday.OvertimePay.ToString("F")</td> <td>@wdWeek2Sunday.OvertimePay.ToString("F")</td> </tr> <tr style="background-color: #D1AE81; color: #6E5028"> <td style="width: 120px; font-weight: bold">Net Pay</td> <td>@wdWeek2Monday.NetPay.ToString("F")</td> <td>@wdWeek2Tuesday.NetPay.ToString("F")</td> <td>@wdWeek2Wednesday.NetPay.ToString("F")</td> <td>@wdWeek2Thursday.NetPay.ToString("F")</td> <td>@wdWeek2Friday.NetPay.ToString("F")</td> <td>@wdWeek2Saturday.NetPay.ToString("F")</td> <td>@wdWeek2Sunday.NetPay.ToString("F")</td> </tr> </table> <hr /> <p>@ViewBag.ErrorMessage</p> }
@{ ViewBag.Title = "Payroll Start-Up"; } <h2 class="text-center">Payroll Start-Up</h2> <div class="tbl-empl"> @using (Html.BeginForm("PayrollPreparation", "Payroll", FormMethod.Post, new { name = "frmPayrollPreparation" })) { <table> <tr> <td style="width: 140px">Enter Time Sheet #:</td> <td>@Html.TextBox("TimeSheetNumber")</td> </tr> <tr> <td> </td> <td> <input type="submit" name="btnDisplayPayroll" value="Display Payroll" style="width: 160px" /> </td> </tr> </table> } </div>
Removing a Value or Object from a Collection
Removing an Item from a Collection
To remove a value or an object from a collection, you have various options. To first look cfor an item before deleting it, both the ArrayList and the List classes are equipped with a method named Remove. Its syntax is:
public virtual void Remove(object value); public bool Remove(T value);
This method accepts as argument the value or the object to delete. Here is an example of calling this method:
@{
ViewBag.Title = "Chemistry";
}
@{
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
molecules.Add("Ozone");
molecules.Add("Oxygen");
molecules.Add("Helium");
molecules.Add("Sulfuric Acid");
molecules.Add("Carbon Dioxide");
}
<ul>
@foreach(string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
@{
molecules.Remove("Helium");
}
<ul>
@foreach (string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
To let you delete an item based on its index within the collection, the classes are equipped with a method named RemoveAt. Its syntax is:
public virtual void RemoveAt(int index); public void RemoveAt(int index);
With this method, the position of the item is passed as argument. Here is an example:
@{
ViewBag.Title = "Chemistry";
}
@{
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
molecules.Add("Ozone");
molecules.Add("Oxygen");
molecules.Add("Helium");
molecules.Add("Sulfuric Acid");
molecules.Add("Carbon Dioxide");
}
<ul>
@foreach(string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
@{
molecules.RemoveAt(2);
}
<ul>
@foreach (string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
If the position is not valid because either it is lower or higher than the current Count, the compiler would throw an ArgumentOutOfRangeException exception.
Clearing a List
To remove all items from a list at once, you can call the Clear() method of either the ArrayList or the List class. Its syntax is:
Here is an example of calling this method:
@{
ViewBag.Title = "Chemistry";
}
@{
System.Collections.ArrayList molecules = new System.Collections.ArrayList();
molecules.Add("Ozone");
molecules.Add("Oxygen");
molecules.Add("Helium");
molecules.Add("Sulfuric Acid");
molecules.Add("Carbon Dioxide");
}
@if( molecules.Count > 0)
{
<ul>
@foreach(string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
}
else
{
<p>There is no molecule to show.</p>
}
@{
molecules.Clear();
}
@if (molecules.Count > 0)
{
<ul>
@foreach (string molecule in molecules)
{
<li>@molecule</li>
}
</ul>
}
else
{
<p>There is no molecule to show.</p>
}
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2021, FunctionX | Next |
|