Introduction to Arrays
Introduction to Arrays
A Series of Similar Items
Introduction to Lists
A list is a group of items. Normally, the items should be of the same type such as a group of people, a group of houses, a group of countries, etc. There are various ways you can programmatically create and manage a list.
Practical Learning: Introducing Arrays
body { } .bold { font-weight: bold; } .text-right { text-align: right; } .top-bar { border-bottom: 6px solid blue; background-color: #000000 !important; } .navbar-light .navbar-brand { color: white; } .navbar-light .navbar-brand:hover { color: yellow; } .navbar-light .navbar-brand:focus { color: khaki; } .navbar-light .navbar-brand { font-family: Georgia, Garamond, 'Times New Roman', serif; } .nav-link { font-family: Georgia, Garamond, 'Times New Roman', serif; } .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Countries Statistics</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/CountriesStatistics.css" asp-append-version="true" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">Countries Statistics</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a> </li> </ul> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> <p class="text-center common-font">© 2022 - Countries Statistics - <a asp-area="" asp-page="/Privacy">Privacy</a></p> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
Introduction to Arrays
So far, to use a series of items, we were declaring a variable for each of them. If the list was made of numbers, we would declare variables for such numbers as follows:
@{
double number1 = 12.44
double number2 = 525.38;
double number3 = 6.28;
double number4 = 2448.32;
double number5 = 632.04;
}
Instead of using individual variables that share the same characteristics, you can group the values in one entity and use that entity as one unit or a regular variable. This group is called an array. Therefore, an array is a group of items with the following characteristics:
Before creating an array, you must first specify the type its items will be made of. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.
After deciding about the type of data of each item that makes up the series, you must use a common name to identify them. The name is the name for the variable that all items of the array will use. The name of an array follows the rules of names of variables. In our lessons, since we consider that an array is a group of values, we will name our array variables in plural.
Unlike a regular list that can contain any number of items, an array has a fixed or constant number of items. Therefore, you must specify the number of items that will constitute the array. The number of items of an array is included in square brackets, as in [5].
An array is considered a reference type. Therefore, an array requests its memory using the new operator. Based on this, one of the formulas to create an array is:
data-type[] variable-name = new data-type[number];
Alternatively, you can use the var or the dynamic keyword to create an array. The formulas to use would be:
var variable-name = new data-type[number]; dynamic variable-name = new data-type[number];
In these formulas, the data-type can be one of the types we have used so far (int (or one of its variants), bool, float, double, decimal, string, etc). It can also be the name of a class, or structure, or record, etc, as we will learn. Like a normal variable, an array must have a name, represented in our formulas as variable-name. The square brackets on the left of the assignment operator are used to let the compiler know that you are creating an array instead of a regular variable. The new operator allows the compiler to reserve memory. The number is used to specify the number of items of the group.
Based on the above formula, here is an example of an array variable:
@{
double[] numbers = new double[5];
}
Here are examples using the var or the dynamic keyword:
@{
double[] numbers = new double[5];
var distances = new float[8];
dynamic values = new int[3];
}
Introduction to the Array Class
To support arrays, the .NET Framework provides a class named Array. The Array class is defined in the System namespace. Whenever you create or use an array, it is actually an object of type Array. This class provides various properties and methods that can be used to manage an array.
Initializing an Array
Introduction
When creating an array, you can specify the number of items that make up its group. Each item of the series is referred to as a member, or an element, or an item, or an object, of the array. Once the array has been created, each one of its members is initialized with a default value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array. You have many options.
Initializing Each Item
An array is primarily a variable; it is simply meant to carry more than one value. There are many techniques you can use to initialize an array. If you have declared an array as done above, to initialize it, you can access each one of its members and assign it a desired but appropriate value.
In algebra, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case, the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A C# array is zero-based. This means that the first member of the array has an index of 0, the second has an index of 1, and so on. In algebra, the series would be represented as X0, X1, X2, X3, and X4.
In C#, the index of a member of an array is written in its own square brackets. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:
@{ double[] numbers = new double[5]; numbers[0] = 12.44; numbers[1] = 525.38; numbers[2] = 6.28; numbers[3] = 2448.32; numbers[4] = 632.04; }
Initializing an Array of Items
Besides this technique, you can also initialize the array as a whole when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type the values of the array members between curly brackets and separated by commas. Here is an example:
@{ double[] numbers = new double[5] { 12.44, 525.38, 6.28, 2448.32, 632.04 }; }
If you use this second technique, you don't have to specify the number of items in the series. In this case, you can leave the square brackets empty. Here is an example:
@{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
Since the data type on the left side of the assignment operator indicates the types of the values of the array, you can omit the data type on the right side. Here is an example:
{
double[] numbers = new[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
If you use this technique, you must not enter the size of the array in the square brackets. In the above two cases that you leave the square brackets empty, the compiler will figure out the number of items.
Since the declaration on the left side of the assignment operator indicates that you are creating an array, you don't need to indicate it on the right side of the assignment operator. Here is an example:
{
double[] numbers = { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
The Length or Size of an Array
We saw that if you declare an array variable but don't initialize it, you must specify the number of elements of the array. This number is passed inside the second pair of square brackets, as a constant integer. Here is an example:
@{
double[] numbers = new double[5];
}
If the array exists already, to assist you with finding out the number of elements in it, the Array class provides a read-only property named Length:
public int Length { get; }
Therefore, to know the number of items that an array contains, get the value of the Length property.
Introduction to Accessing the Members of an Array
After initializing an array, which means after each of its members has been given a value, you can access a member of the array to get, manipulate or even change its value. To access a member of the array, you use the square brackets as we saw above. As done for normal variables, one of the reasons of accessing a member of an array is to display its value. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@{
double[] numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };
}
<pre>Number: @numbers[3]
===========================</pre>
This would produce:
Number: 2448.32 ===========================
In the same way, you can access 1, a few or all members of an array.
Remember that, to access a member of an array, pass its index to the square brackets of the variable. If you pass an index higher than the number of items in the array, the compiler will throw an exception.
Practical Learning: Creating and Using Arrays
@page @model IndexModel @{ 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 }; } <h2 class="common-font bold text-center">United Mexican States</h2> <table border="6" class="common-font table-bordered" align="center"> <tr> <td class="text-center"> </td> <td> </td> <td colspan="2" class="text-center bold">Area</td> <td class="text-center bold">Admission to Federation</td> <td> </td> </tr> <tr> <td class="text-center short-text">#</td> <td class="bold">State Name</td> <td class="text-center bold">Sqr Kms</td> <td class="text-center bold">Sqr Miles</td> <td class="text-center bold">Order</td> <td class="bold">Capital</td> </tr> <tr> <td class="text-center">1</td><td>@states[0]</td><td class="text-right">@areasSqrKms[0]</td><td class="text-right">@areasSqrMiles[0]</td><td class="text-center">@ordersOfAdmissionToFederation[0]</td><td>@capitals[0]</td> </tr> <tr> <td class="text-center">2</td><td>@states[1]</td><td class="text-right">@areasSqrKms[1]</td><td class="text-right">@areasSqrMiles[1]</td><td class="text-center">@ordersOfAdmissionToFederation[1]</td><td>@capitals[1]</td> </tr> <tr> <td class="text-center">3</td><td>@states[2]</td><td class="text-right">@areasSqrKms[2]</td><td class="text-right">@areasSqrMiles[2]</td><td class="text-center">@ordersOfAdmissionToFederation[2]</td><td>@capitals[2]</td> </tr> <tr> <td class="text-center">4</td><td>@states[3]</td><td class="text-right">@areasSqrKms[3]</td><td class="text-right">@areasSqrMiles[3]</td><td class="text-center">@ordersOfAdmissionToFederation[3]</td><td>@capitals[3]</td> </tr> <tr> <td class="text-center">5</td><td>@states[4]</td><td class="text-right">@areasSqrKms[4]</td><td class="text-right">@areasSqrMiles[4]</td><td class="text-center">@ordersOfAdmissionToFederation[4]</td><td>@capitals[4]</td> </tr> <tr> <td class="text-center">6</td><td>@states[5]</td><td class="text-right">@areasSqrKms[5]</td><td class="text-right">@areasSqrMiles[5]</td><td class="text-center">@ordersOfAdmissionToFederation[5]</td><td>@capitals[5]</td> </tr> <tr> <td class="text-center">7</td><td>@states[6]</td><td class="text-right">@areasSqrKms[6]</td><td class="text-right">@areasSqrMiles[6]</td><td class="text-center">@ordersOfAdmissionToFederation[6]</td><td>@capitals[6]</td> </tr> <tr> <td class="text-center">8</td><td>@states[7]</td><td class="text-right">@areasSqrKms[7]</td><td class="text-right">@areasSqrMiles[7]</td><td class="text-center">@ordersOfAdmissionToFederation[7]</td><td>@capitals[7]</td> </tr> <tr> <td class="text-center">9</td><td>@states[8]</td><td class="text-right">@areasSqrKms[8]</td><td class="text-right">@areasSqrMiles[8]</td><td class="text-center">@ordersOfAdmissionToFederation[8]</td><td>@capitals[8]</td> </tr> <tr> <td class="text-center">10</td><td>@states[9]</td><td class="text-right">@areasSqrKms[9]</td><td class="text-right">@areasSqrMiles[9]</td><td class="text-center">@ordersOfAdmissionToFederation[9]</td><td>@capitals[9]</td> </tr> <tr> <td class="text-center">11</td><td>@states[10]</td><td class="text-right">@areasSqrKms[10]</td><td class="text-right">@areasSqrMiles[10]</td><td class="text-center">@ordersOfAdmissionToFederation[10]</td><td>@capitals[10]</td> </tr> <tr> <td class="text-center">12</td><td>@states[11]</td><td class="text-right">@areasSqrKms[11]</td><td class="text-right">@areasSqrMiles[11]</td><td class="text-center">@ordersOfAdmissionToFederation[11]</td><td>@capitals[11]</td> </tr> <tr> <td class="text-center">13</td><td>@states[12]</td><td class="text-right">@areasSqrKms[12]</td><td class="text-right">@areasSqrMiles[12]</td><td class="text-center">@ordersOfAdmissionToFederation[12]</td><td>@capitals[12]</td> </tr> <tr> <td class="text-center">14</td><td>@states[13]</td><td class="text-right">@areasSqrKms[13]</td><td class="text-right">@areasSqrMiles[13]</td><td class="text-center">@ordersOfAdmissionToFederation[13]</td><td>@capitals[13]</td> </tr> <tr> <td class="text-center">15</td><td>@states[14]</td><td class="text-right">@areasSqrKms[14]</td><td class="text-right">@areasSqrMiles[14]</td><td class="text-center">@ordersOfAdmissionToFederation[14]</td><td>@capitals[14]</td> </tr> <tr> <td class="text-center">16</td><td>@states[15]</td><td class="text-right">@areasSqrKms[15]</td><td class="text-right">@areasSqrMiles[15]</td><td class="text-center">@ordersOfAdmissionToFederation[15]</td><td>@capitals[15]</td> </tr> <tr> <td class="text-center">17</td><td>@states[16]</td><td class="text-right">@areasSqrKms[16]</td><td class="text-right">@areasSqrMiles[16]</td><td class="text-center">@ordersOfAdmissionToFederation[16]</td><td>@capitals[16]</td> </tr> <tr> <td class="text-center">18</td><td>@states[17]</td><td class="text-right">@areasSqrKms[17]</td><td class="text-right">@areasSqrMiles[17]</td><td class="text-center">@ordersOfAdmissionToFederation[17]</td><td>@capitals[17]</td> </tr> <tr> <td class="text-center">19</td><td>@states[18]</td><td class="text-right">@areasSqrKms[18]</td><td class="text-right">@areasSqrMiles[18]</td><td class="text-center">@ordersOfAdmissionToFederation[18]</td><td>@capitals[18]</td> </tr> <tr> <td class="text-center">20</td><td>@states[19]</td><td class="text-right">@areasSqrKms[19]</td><td class="text-right">@areasSqrMiles[19]</td><td class="text-center">@ordersOfAdmissionToFederation[19]</td><td>@capitals[19]</td> </tr> <tr> <td class="text-center">21</td><td>@states[20]</td><td class="text-right">@areasSqrKms[20]</td><td class="text-right">@areasSqrMiles[20]</td><td class="text-center">@ordersOfAdmissionToFederation[20]</td><td>@capitals[20]</td> </tr> <tr> <td class="text-center">22</td><td>@states[21]</td><td class="text-right">@areasSqrKms[21]</td><td class="text-right">@areasSqrMiles[21]</td><td class="text-center">@ordersOfAdmissionToFederation[21]</td><td>@capitals[21]</td> </tr> <tr> <td class="text-center">23</td><td>@states[22]</td><td class="text-right">@areasSqrKms[22]</td><td class="text-right">@areasSqrMiles[22]</td><td class="text-center">@ordersOfAdmissionToFederation[22]</td><td>@capitals[22]</td> </tr> <tr> <td class="text-center">24</td><td>@states[23]</td><td class="text-right">@areasSqrKms[23]</td><td class="text-right">@areasSqrMiles[23]</td><td class="text-center">@ordersOfAdmissionToFederation[23]</td><td>@capitals[23]</td> </tr> <tr> <td class="text-center">25</td><td>@states[24]</td><td class="text-right">@areasSqrKms[24]</td><td class="text-right">@areasSqrMiles[24]</td><td class="text-center">@ordersOfAdmissionToFederation[24]</td><td>@capitals[24]</td> </tr> <tr> <td class="text-center">26</td><td>@states[25]</td><td class="text-right">@areasSqrKms[25]</td><td class="text-right">@areasSqrMiles[25]</td><td class="text-center">@ordersOfAdmissionToFederation[25]</td><td>@capitals[25]</td> </tr> <tr> <td class="text-center">27</td><td>@states[26]</td><td class="text-right">@areasSqrKms[26]</td><td class="text-right">@areasSqrMiles[26]</td><td class="text-center">@ordersOfAdmissionToFederation[26]</td><td>@capitals[26]</td> </tr> <tr> <td class="text-center">28</td><td>@states[27]</td><td class="text-right">@areasSqrKms[27]</td><td class="text-right">@areasSqrMiles[27]</td><td class="text-center">@ordersOfAdmissionToFederation[27]</td><td>@capitals[27]</td> </tr> <tr> <td class="text-center">29</td><td>@states[28]</td><td class="text-right">@areasSqrKms[28]</td><td class="text-right">@areasSqrMiles[28]</td><td class="text-center">@ordersOfAdmissionToFederation[28]</td><td>@capitals[28]</td> </tr> <tr> <td class="text-center">30</td><td>@states[29]</td><td class="text-right">@areasSqrKms[29]</td><td class="text-right">@areasSqrMiles[29]</td><td class="text-center">@ordersOfAdmissionToFederation[29]</td><td>@capitals[29]</td> </tr> <tr> <td class="text-center">31</td><td>@states[30]</td><td class="text-right">@areasSqrKms[30]</td><td class="text-right">@areasSqrMiles[30]</td><td class="text-center">@ordersOfAdmissionToFederation[30]</td><td>@capitals[30]</td> </tr> </table> }
Primary Operations on Lists
Introduction
When you have accessed an item of an array, you have its value. You can then perform any appropriate operation on it.
Operations on Numbers
We have already tested the regular algebraic operations that can be permormed on variables. Those operations can also be performed on items of an array. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; float[] number = new[] { 44.50f }; double[] payRates = new[] { 15.55d, 30.05d, 24.80d, 17.95d }; int addition = naturals[1] + naturals[3]; double seventh = naturals[2] / 7.00d; decimal salary = (decimal)(payRates[2] * number[0]); string strSalary = $"{salary:F}"; } <pre>============================ @naturals[1] + @naturals[3] = @addition @naturals[2] / 2 = @seventh Salary: @strSalary ============================</pre>
This would produce:
============================ 7594 + 5050 = 12644 3708 / 2 = 529.7142857142857 Salary: 1103.60 ============================
Operations on Strings
We already know that various types of operations can be performed on strings. The primary operation performed on string is the addition. You can perform that operation on items of an array that contains strings. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ string[] identifier = new[] { "Lincoln", "Abraham " }; string[] name = new[] { "Clinton", "William", "Jefferson" }; string full = identifier[1] + identifier[0]; string complete = name[1] + " " + name[2] + " " + name[0]; } <pre>=============================== Name: @full Name: @complete ===============================</pre>
This would produce:
=============================== Name: Abraham Lincoln Name: William Jefferson Clinton ===============================
Anonymous Arrays
Introduction
In previous sections, when creating an array, we were specifying its type. As seen in our introduction to variables, a good feature of the var or the dynamic keyword is that, when using them to declare and initialize a variable, you ask the compiler to figure out what type of data the variable is holding. This concept is also valid for an array.
An anonymous array is an array variable whose type is left to the compiler to determine, based on the types of values of the array.
Creating an Anonymous Array
As done for variables so far, when creating an array, you can use the var or the dynamic keyword, initialize the array, but not specify its data type. The formula to use is:
var array-name = new[] { initialization };
The formula is almost similar to that of a normal array, with keywords and operators you are already familiar with. The array-name is the name of the variable. Notice that the new keyword is directly followed by the square brackets. In the curly brackets, you must initialize the array by providing the necessary values. For the compiler to be able to figure out the type and amount of memory to allocate for the array variable, all values must be of the same type or the same category:
@{
var naturals = new[] { 2735, 20, 3647597, 3408, 957 };
dynamic values = new[] { 0x91FF22, 8168, 0x80080, 0xF822FF, 202684 };
}
@{
var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F };
var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 };
var values = new[] { 17.230M, 4808237M, 222.4203M, 948.002009M };
}
@{
var friends = new[] { "Mark", "Frank", "Charlotte", "Jerry" };
}
Accessing the Members of an Anonymous Array
After creating an anonymous array, you can access each member using its index. Here are two examples:
@page @model Exercises.Pages.ExerciseModel @{ var singles = new[] { 1244F, 525.38F, 6.28F, 2448.32F, 632.04F }; var doubles = new[] { 3.212D, 3047.098D, 732074.02, 18342.3579 }; } <pre>Number: @singles[2] Number: @doubles[0] ====================</pre>
This would produce:
Number: 6.28 Number: 3.212 ====================
Techniques of Initializing an Array
A Return Value as an Index
When accessing a member of an array using its index, the value between square brackets must be known. Most of the time, it is a constant, but this is not always the case. The rule is that, at the time you open the square brackets, the value must be known, even if it is not a constant. For example, the value can be returned from a function/method. Here is an example:
@{ double[] numbers = new double[5]; numbers[0] = 12.44; numbers[1] = 525.38; numbers[GetIndex()] = 6.28; numbers[3] = 2448.32; numbers[4] = 632.04; } @functions{ int GetIndex() { return 2; } }
Variables as Members of an Array
We have initialized our arrays so far with values we specified directly in the curly brackets. If you have declared and initialized some variables of the same type, you can use them to initialize an array. You use those values in place of the members of the array. Here is an example:
@{ double area = 97394.2204D; double distance = 982.84D; double level = 27D; double quantity = 237957.704D; double[] measures = new double[] { area, distance, level, quantity }; }
Array Members from Constants
The values of the members of an array can come from constant variables. Here is an example:
@{ const double PI = 3.141592653; double squareRootOf2 = 1.414D; double e = 2.718D; const double radiusOfEarth = 6370; // km double ln2 = 0.6931; double[] measures = new double[] { PI, squareRootOf2, e, radiusOfEarth, ln2 }; }
Expressions as Members of an Array
The values of the members of an array can come from calculations. A calculation can come from an initialized variable or made locally in the curly brackets. Here is an example:
@{ const double densityOfWater = 1000; // kg/m3 ; double massOfEarth = 5.98 * 10e24; // kg double earthMoonDistance = 2.39 * 10e5; // miles double[] Measures = new double[] { densityOfWater, 9.30 * 10.7, massOfEarth, earthMoonDistance }; }
The rule to follow is that, at the time the array is created, the compiler must be able to know exactly the value of each member of the array, no guessing.
Hexadecimal Values as Members of an Array
If the members of an array are integers, you can use decimals, hexadecimal values, or a combination of both. Here is an example:
@{
int red = 0xFF0000;
int someColor = 0x800000;
int[] colors = new int[] { 2510, red, 818203, someColor, 0xF28AC };
}
Boolean Values as Members of an Array
The members of an array can hold Boolean values. Here is an example:
@{
bool[] fullTimeStudents = new bool[] { true, true, true, false, true, false };
}
You can also use the var or the dynamic keyword to declare the variable, as long as each element can be evaluated to true or false. Here is an example:
@{
var qualifications = new[] { true, true, false, true, false };
}
Each value of a Boolean array must be evaluated to true or false. This means that you can use variables or expressions as members of the array. Here is an example:
@{ bool[] conparisons = new bool[] { 25 < 10, house1Value == house2Value, true }; }
A Returned Value as a Member of an Array
The value of a member of an array can be the returned value of a method. Here is an example:
@{ double[] numbers = new double[5]; numbers[0] = 12.44; numbers[1] = 525.38; numbers[GetIndex()] = 6.28; numbers[3] = 2448.32; numbers[4] = GetDistance(); } @functions{ public class Exercise { int GetIndex() { return 2; } double GetDistance() { return 632.04; } } }
As a result, both the index and the value can come from methods. Here is an example:
@{ double[] numbers = new double[5]; numbers[0] = 12.44; numbers[1] = 525.38; numbers[GetIndex()] = 6.28; numbers[SpecifyIndex()] = SpecifyValue(); numbers[4] = GetDistance(); } @functions{ public class Exercise { int GetIndex() { return 2; } int SpecifyIndex() { return 3; } double GetDistance() { return 632.04; } double SpecifyValue() { return 2448.32; } } }
A Range of Items from an Existing Array
Introduction
In previous sections, we learned to create an array as a list of values. Here is an example as a list of letters:
@page
@model Exercises.Pages.ExerciseModel
@{
string[] letters = new[] { "R", "J", "E", "A", "U", "B", "H", "S" };)
}
We saw that such a variable represents a list of values and each values is in a specific position, from 0, which is the first position, to the last position, which is the total number of items minus 1. Consequently, the items of an array are in a range from the first to the last. To identify the range of items of an array, you use an operator represented as two consecutive periods: ..
To create an array of items of an existing array, you can include two periods in square brackets applied to the original array. that operation would give you a new array. You can use that new array as you see fit. For example, you can assign that new array to an array variable. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@{
string[] letters = new[] { "R", "J", "E", "A", "U", "B", "H", "S" };
string[] allItems = letters[..];
}
You can then access an item of the new variable using that item's index. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ string[] letters = new[] { "R", "J", "E", "A", "U", "D", "H", "S" }; string[] allItems = letters[..]; } <pre>Letter: @allItems[0] Letter: @allItems[2] Letter: @allItems[5] ====================</pre>
This would produce:
Letter: R Letter: E Letter: B ====================
A variable is necessary only if you want to store the new array in the computer memory. Otherwise, you can use the array directly where it is needed. For example, if you to access an item of the range, type the array as we did above or as we will need in the next sections, then add another combination of []. In those square brackets, type the index of the item you want to access. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ string[] letters = new[] { "R", "J", "E", "A", "U", "D", "H", "S" }; string[] allItems = letters[..]; string[] typesOfCameras = new[] { "Point and Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; } <pre>========================================== Color: @allItems[0]@allItems[2]@allItems[5] ------------------------------------------ Type of Camera: @typesOfCameras[..][1] Type of Camera: @typesOfCameras[..][3] ==========================================</pre>
This would produce:
========================================== Color: RED ------------------------------------------ Type of Camera: DSLR Type of Camera: Instant (Polaroid) Camera ==========================================
The First Element of an Array
We already know that the elements of an array are ordered with the first item at Position 0. Therefore, to get the first item of an array, simply write the square brackets and pass 0 in them. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" }; double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 }; string[] typesOfCameras = new[] { "Point of Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; } <pre>===================== Number: @naturals[0] Letter: @letters[0] Price: @prices[0] Camera: @typesOfCameras[0] ======================</pre>
This would produce:
===================== Number: 29 Letter: J Price: 32 Camera: Point of Shoot ======================
The First n Elements of an Array
If you have an array of items, you can create an array that uses the item of that array. This is referred to as a range of items from an existing array. If you have an array of items, the first n elements of the array is the range of items from the first to a specific position of your choice. To get a new array that uses the first n values of an existing array, type the name of the array followed by curly brackets. In the brackets, type .. followed by the ending position within the existing array. If you want, you can assign this operation to a variable. After that, you can access the members of the new array using any of the techniques we have used so far. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ string[] letters = new[] { "J", "o", "h", "n", "n", "y" }; string[] name = letters[..4]; string[] typesOfCameras = new[] { "Point and Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; } <pre>========================================== Name: @name[0]@name[1]@name[2]@name[3] ------------------------------------------ Type of Camera: @typesOfCameras[..2][0] Type of Camera: @typesOfCameras[..2][1] ==========================================</pre>
This would produce:
========================================== Name: John ------------------------------------------ Type of Camera: Point and Shoot Type of Camera: DSLR ==========================================
The Last Element of an Array
There are various ways you can get the last item of an array. The classic way is to first know the number of items in the array, then type the number of elements minus one inside the square brackets. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" }; double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 }; string[] typesOfCameras = new[] { "Point of Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; } <pre>================================ Last Item --------------------------------- Number: @naturals[5 - 1] Letter: @letters[8 - 1] Price: @prices[6 - 1] Camera: @typesOfCameras[4 - 1] =================================</pre>
This would produce:
================================ Last Item --------------------------------- Number: 684 Letter: S Price: 35 Camera: Instant (Polaroid) Camera =================================
The problem is that the above solution requires that you know the number of items in the array, which may require some efforts on your parts. The easier solution is provided by the ^ operator. To use this solution, write this operator in square brackets. On the right side of the operator, type 1. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" }; double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 }; string[] typesOfCameras = new[] { "Point of Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; int natural = naturals[^1]; string letter = letters[^1]; } <pre>================================ Last Item --------------------------------- Number: @natural Letter: @letter Price: @prices[^1] Camera: @typesOfCameras[^1] =================================</pre>
The Last n Elements of an Array
To get the last n elements of an existing array, use the name of an array followed by curly brackets. In the brackets, type the desired starting position within the existing array followed by two periods. That will produce a new array that you can use directly or store that array in an array variable. Either way, you can then use the new array as you see fit. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@{
double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 };
double[] lastThree = prices[3..];
}
<pre>===========================
Last 3 Items: @lastThree[0], @lastThree[1], @lastThree[2]
===========================</pre>
This would produce:
=========================== Last 3 Items: 42, 48.5, 35 ===========================
A Range of Items from an Array
If you have an array of items, you can create an array that uses the item of that array. One way to do this is to specify a ranges of indexes from one starting point to an ending index. To do this, create an opening curly bracket ([) and a closing curly bracket (}). In those brackets, type the index of the starting point, followed by .., and followed by the index of the last point. If you want, you can apply this operation to a variable. After that, you can access the members of the new array using any of the techniques we have used so far. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@{
string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" };
string[] assignment = letters[2..6];
}
<pre>=================
Assignment: @assignment[0]@assignment[1]@assignment[2]@assignment[3]
=================</pre>
This would produce:
================= Assignment: READ =================
An Array Element from the End of an Array
You already know that, to get an array element from the start of an array, apply the square brackets to the name of the array. In the square brackets, type the 0-based index of the item. To get an item from the end, in the square brackets type the number of items minus the 1-based position of the item (we use "1-based" because the last item is at Position 1 from end, unlike the position of the first item which is 0). Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" }; double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 }; string[] typesOfCameras = new[] { "Point of Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; int natural = naturals[5 - 2]; string letter = letters[8 - 4]; } <pre>============================================================= Lists of Items ------------------------------------------------------------- Natural Numbers: @naturals[0], @naturals[1], @naturals[2], @naturals[3], @naturals[4] Letters: @letters[0], @letters[1], @letters[2], @letters[3], @letters[4], @letters[5], @letters[6], @letters[7] Prices: @prices[0], @prices[1], @prices[2], @prices[3], @prices[4], @prices[5] Cameras: @typesOfCameras[0], @typesOfCameras[1], @typesOfCameras[2], @typesOfCameras[3] ============================================================== Second number from end: @natural Fourth letter from end: @letter First price from end: @prices[6 - 1] Third camera from end: @typesOfCameras[4 - 3] ==============================================================</pre>
This would produce:
============================================================== Lists of Items -------------------------------------------------------------- Natural Numbers: 29, 7594, 3708, 5050, 684 Letters: J, H, R, E, A, D, U, S Prices: 32, 44.5, 35, 42, 48.5, 35 Cameras: Point of Shoot, DSLR, 360, Instant (Polaroid) Camera ============================================================== Second number from end: 5050 Fourth letter from end: A First price from end: 35 Third camera from end: DSLR ==============================================================
This can be complicated or confusing. The solution is to use the ^ operator. This time, write the 1-based index on the right side of the operator. Here are examples:
@page @model Exercises.Pages.ExerciseModel @{ int[] naturals = new[] { 29, 7594, 3708, 5050, 684 }; string[] letters = new[] { "J", "H", "R", "E", "A", "D", "U", "S" }; double[] prices = new[] { 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 }; string[] typesOfCameras = new[] { "Point of Shoot", "DSLR", "360", "Instant (Polaroid) Camera" }; int natural = naturals[^2]; //[5 - 2]; string letter = letters[^4]; //[8 - 4]; } <pre>============================================================= Lists of Items ------------------------------------------------------------- Natural Numbers: @naturals[0], @naturals[1], @naturals[2], @naturals[3], @naturals[4] Letters: @letters[0], @letters[1], @letters[2], @letters[3], @letters[4], @letters[5], @letters[6], @letters[7] Prices: @prices[0], @prices[1], @prices[2], @prices[3], @prices[4], @prices[5] Cameras: @typesOfCameras[0], @typesOfCameras[1], @typesOfCameras[2], @typesOfCameras[3] ============================================================== Second number from end: @natural Fourth letter from end: @letter First price from end: @prices[^1] Third camera from end: @typesOfCameras[^3] ==============================================================</pre>
Introduction
An array is primarily is a type in its own right. As such, it can be used in the various ways we have dealt with data types so far. The main issue to keep in mind is that the type of an array is a series of values.
Returning an Array from a Function
Like a normal variable, an array can be returned from a function. This means that the function would return a variable that carries various values. To start, when creating the function, you must specify its data type as an array. That is, write the desired data type of the array followed by empty square brackets. Here is an example:
@functions{
int[] Initialize()
{
}
}
In the body of the function, perform any operation or processing your want. Before the closing curly bracket, you must return a value that holds an array. As one way you can do this, in the body of the function, you can create an initialize an array variable, then return that variable. Here is an example:
@functions{
public int[] Initialize()
{
int[] coords = new int[] { 12, 5, -2, -2 };
return coords;
}
}
If you know the array you want to return and you don't need to use it many time, you don't have to declare a variable for it. You can return it directly on the function. This can be done as follows:
@functions{
string[] CreateWaterVehicles()
{
return new string[] { "canoe", "boat", "ship", "submarine" };
}
}
You can omit the data type. This can be done as follows:
@functions
{
string[] CreateWaterVehicles()
{
return new[] { "canoe", "boat", "ship", "submarine" };
}
}
In the function, you can create a conditional statement that specifies the returned array based on a condition. Here is an example:
@functions{ string[] GetPronouns(int nbr) { string[] pronouns = new string[6]; if (nbr == 1) pronouns = new string[] { "I", "you", "he/she", "we", "you", "they" }; else if (nbr == 2) pronouns = new string[] { "me", "you", "him/her", "us", "you", "them" }; else if (nbr == 3) pronouns = new string[] { "myself", "yourself", "himself/herself", "ourselves", "yourselves", "themselves" }; else pronouns = new string[] { "unknown", "unknown", "unknown", "unknown", "unknown", "unknown" }; return pronouns; } }
Once again, remember that you use a variable if you are planning to use a value many times. Otherwise, you may not need a variable. Here is an example:
@functions{ string[] GetPronouns(int nbr) { if (nbr == 1) return new string[] { "I", "you", "he/she", "we", "you", "they" }; else if (nbr == 2) return new string[] { "me", "you", "him/her", "us", "you", "them" }; else if (nbr == 3) return new string[] { "myself", "yourself", "himself/herself", "ourselves", "yourselves", "themselves" }; else return new string[] { "unknown", "unknown", "unknown", "unknown", "unknown", "unknown" }; } }
Getting the Returned Array of a Function
When a function returns an array, that function can be assigned to an array variable declared locally where you want to use it. Remember to initialize a variable with such a function only if the variable is an array. Here is an example:
@{ int[] system = new int[4]; system = Initialize(); } @functions{ int[] Initialize() { int[] coords = new int[] { 12, 5, -2, -2 }; return coords; } }
Once you have the returned array from the function, you can use that array normally. Here is an example:
@page @model Exercises.Pages.ExerciseModel @{ int[] system = new int[4]; system = Initialize(); } @functions { int[] Initialize() { var coords = new int[] { 12, 5, 625, -2 }; return coords; } } <pre>Number: @system[0] Number: @system[1] Number: @system[2] Number: @system[3] ====================</pre>
This would produce:
Number: 12 Number: 5 Number: 625 Number: -2 ====================
The function could also be called as follows:
@{
int[] system = Initialize();
}
@functions{
int[] Initialize()
{
int[] coords = new int[] { 12, 5, -2, -2 };
return coords;
}
}
You can also declare the variable using either the var or the dynamic keyword. Those keywords don't need square brackets. Here are examples:
@{
int[] system = Initialize();
}
functions{
int[] Initialize()
{
var coords = new int[] { 12, 5, -2, -2 };
return coords;
}
}
Like a regular variable, an array can be passed as argument. To proceed, in the parentheses of a function, provide the data type, empty square brackets, and the name of the argument. Here is an example:
@functions{
void ShowPoints(int[] points)
{
}
}
When an array has been passed to a function, it can be used in the body of the function as any array would be, following the rules of array variables. For example, you can display its values. The simplest way you can use an array is to display the values of its members. This could be done as follows:
@using static System.Console @functions{ int[] Initialize() { var coords = new int[] { 12, 5, 625, -2 }; return coords; } void CreateCoordinate(int[] pts) { WriteLine("P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")"); } }
To call a function that takes an array as argument, simply type the name of the array in the parentheses of the called function. Here is an example:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@{
int[] geos = Initialize();
CreateCoordinate(geos);
}
@functions{
int[] Initialize()
{
var coords = new int[] { 12, 5, 625, -2 };
return coords;
}
void CreateCoordinate(int[] pts)
{
WriteLine("P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")");
}
}
Other Techniques of Passing Arrays as Arguments
As is the case for variables of primitive types, you can pass an array by reference. To do that, in the parentheses of the function, before the ref keyword. This can be done as follows:
@functions{
void Initialize(ref int[] coords)
{
}
}
When you call such a function, precede the argument with the ref keyword. This can be done as follows:
@{
int[] points = new int[4];
Initialize(ref points);
}
@functions{
void Initialize(ref int[] coords)
{
}
}
As is the case for values of primitive types, if you pass an array by reference, the function can modify the array. If that happens, when the function exits, the changes made on the array are kept. Here is an example:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ int[] points = new int[4]; Initialize(ref points); CreateCoordinate(points); } @functions { void Initialize(ref int[] coords) { coords = new int[] { 6, 3, -5, 0 }; } void CreateCoordinate(int[] pts) { WriteLine("Points Coordinates: P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")"); } }
Instead of just one, you can create a function that receives more than one array and you can create a function that receives a combination of one or more arrays and one or more regular arguments. You can also create a function that uses one or more arrays as parameter(s) and returns a regular value of a primitive type.
Passing an Array Out
As seen for passing an argument by reference, you can pass an array out. We saw that, when passing an array using the ref keyword, the function that receives the array doesn't have to initialize it. If the array was already initialized by the function that is making the call, the called function can simply change the values of the elements of the array. On the other hand, if you pass an array using the out keyword, the function that receives the out array must initialize it before exiting. Here is an example:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ int[] points = new int[4]; Initialize(out points); CreateCoordinate(points); WriteLine("======================================"); } @functions { void Initialize(out int[] coords) { coords = new int[] { 1, 4, 2, -4 }; } void CreateCoordinate(int[] pts) { WriteLine("Points Coordinates: P(" + pts[0] + ", " + pts[1] + "), Q(" + pts[2] + ", " + pts[1] + ")"); } }
Passing a Varied Number of Parameters
When you pass an array as argument or pass a combination of arrays and non-array arguments, when you call the function, you must pass the exact number of arguments. That is, you must know the number of arguments the function will process. An alternative to this is to pass only one array as argument. Then, when, or every time, you call the function, you can pass any number of values you want. That is, at one time you can call the function and pass 2 values. At another time, you can call the same function but pass more arguments to it.
To create a function that receives a varied number of arguments, in the parentheses of the method, type the params keyword followed by an array. Here is an example:
@functions{ void ShowPoints(params int[] points) { } }
As mentioned already, when calling the function, you can pass the number of arguments you want. It's important to know that the function that receives a params argument doesn't know the number of arguments it will receive when it is called. This means that you must find a way to access the arguments and you must find a way for the function to know the number of arguments it received. Because this information is not known to the function, the Array class provides a property named Length that holds the size of the array. Here are examples:
@page
@model Exercises.Pages.ExerciseModel
@using static System.Console
@functions
{
void Describe(params int[] pts)
{
int dimension = pts.Length;
if (dimension == 1)
{
WriteLine("The point is located on a line.");
}
else if (dimension == 2)
{
WriteLine("The point is located on a Cartesian coordinate system.");
}
else if (dimension == 3)
{
WriteLine("The point is located on a 3-D coordinate system.");
}
else
{
WriteLine("The point is located on a multi-dimensional system.");
}
}
}
Here are examples of calling a function that receives a params argument:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ int[] system = new int[4]; WriteLine(Points Coordinates"); WriteLine("======================================================"); // The method is called with one argument WriteLine("Coordinate: -6"); Describe(-6); WriteLine("------------------------------------------------------"); // The method is called with 4 arguments Describe(2, 2, 5, -3); WriteLine("Coordinates: 2, 2, 5, -3"); WriteLine("------------------------------------------------------"); // The method is called with two arguments WriteLine("Coordinates: 2, 5"); Describe(2, 5); WriteLine("------------------------------------------------------"); // The method is called with three arguments WriteLine("Coordinates: -4, 3, 1"); Describe(-4, 3, 1); WriteLine("====================================================== } @functions{ void Describe(params int[] pts) { int dimension = pts.Length; if (dimension == 1) { WriteLine("The point is located on a line."); } else if (dimension == 2) { WriteLine("The point is located on a Cartesian coordinate system."); } else if (dimension == 3) { WriteLine("The point is located on a 3-D coordinate system."); } else { WriteLine("The point is located on a multi-dimensional system."); } } }
This would produce:
Points Coordinates ====================================================== Coordinate: -6 The point is located on a line. ------------------------------------------------------ The point is located on a multi-dimensional system. Coordinates: 2, 2, 5, -3 ------------------------------------------------------ Coordinates: 2, 5 The point is located on a Cartesian coordinate system. ------------------------------------------------------ Coordinates: -4, 3, 1 The point is located on a 3-D coordinate system. ======================================================
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2022, FunctionX | Monday 14 February 2022 | Next |
|