Home

Common Operations on Arrays

Routine List-Based Operations on Arrays

Introduction

As mentioned in previous lessons, an array is a list of items. To help you manage those items, the .NET Framework provides the Array class. That class is equipped with methods to perform various types of operations on arrays.

To create an array, you can use either the Array class or the array techniques in the C# language.

Practical LearningPractical Learning: Introducing Arrays and Classes

  1. Start Microsoft Visual Studio and create a new Windows Forms application named CountriesStatistics7
  2. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> New Item...
  3. In the left frame of the Add New Item dialog box, click Code and, in the middle frame, click Interface
  4. Change the Name to Abbreviated
  5. Click Add
  6. Create a string-based property as follows:
    namespace CountriesStatistics6
    {
        public interface IAbbreviated
        {
            string Abbreviation { get; set; }
        }
    }
    
  7. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> New Item...
  8. In the middle list of the Add New Item dialog box, make sure Interface is selected.
    Change the file name to GovernmentEntity
  9. Click Add
  10. Change the document as follows:
    namespace CountriesStatistics6
    {
        public interface IGovernmentEntity
        {
            string Name    { get; set; }
            int    Area    { get;      }
            string Capital { get; set; }
        }
    }
  11. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> Class...
  12. Change the file Name to Region as the Name of the class
  13. Click Add
  14. Change the document as follows:
    namespace CountriesStatistics6
    {
        public class Region
        {
            public string Designation { get; set; }
            public string Description { get; set; }
        }
    }
  15. In the Solution Explorer, right-click Models -> Add -> Class...
  16. Type State as the name of the file
  17. Press Enter
  18. Change the class as follows:
    namespace CountriesStatistics6
    {
        public class State : IGovernmentEntity, IAbbreviated
        {
            // From the IAbbreviated interface
            public string Abbreviation { get; set; }
    
            // From the IGovernmentEntity interface
            public string Name         { get; set; }
            public int    Area         { get; set; }
            public string Capital      { get; set; }
    
            // New Properties
            public string StateName    => Name;
            public int    AreaSqrMiles => Area;
            public int    AreaSqrKms   { get; set; }
            public Region Region       { get; set; }
            
            public override bool Equals(object obj)
            {
                State stt = (State)obj;
                
                if (stt.Name == Name)
                    return true;
                
                return false;
            }
            
            public override int GetHashCode()
            {
                return base.GetHashCode();
            }
        }
    }
  19. In the Solution Explorer, right-click CountriesStatistics6 -> Add -> Class...
  20. Type Federation
  21. Click Add
  22. Change the document as follows:
    namespace CountriesStatistics6
    {
        public class Federation : State
        {
            public int AdmissionUnionOrder { get; set; }
        }
    }
  23. In the Solution Explorer, double-click Form1.cs to access the form
  24. Design the form as follows:

    Doing Something While a Condition is True

    Control (Name) Text TextAlign
    Label   United States of America Font: Georgia, 20.25pt, style=Bold
    Label   ____________________________________  
    ListView lvwStates  
    View:          Details
    GridLines:     True
    FullRowSelect: True
    Anchor: Top, Bottom, Left, Right

    List View Columns

    (Name) Text TextAlign Width
    colNumber #   25
    colAbbreviation Abbrv Center 40
    colStateName State Name   100
    colAreaSqrKms Area (Sqr Kms) Right 90
    colAreaSqrMiles Area (Sqr Ml) Right 80
    colAdmissionToFederation Adm to Fedrt (Order) Center 130
    colCapital Capital   80
    colRegion Region   120
  25. Right-click the form and click View Code
  26. Change the document as follows:
    using System;
    using System.Windows.Forms;
    
    namespace CountriesStatistics7
    {
        public partial class Form1 : Form
        {
            Federation[] states = new Federation[30];
            Region[] regions = new Region[9];
    
            public Form1()
            {
                InitializeComponent();
    
                Display();
            }
    
            void Display()
            {
                regions[0] = new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." };
                regions[1] = new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." };
                regions[2] = new Region() { Designation = "New England",        Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." };
                regions[3] = new Region() { Designation = "Mid-Atlantic",       Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." };
                regions[4] = new Region() { Designation = "Mountain",           Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." };
                regions[5] = new Region() { Designation = "Pacific",            Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." };
                regions[6] = new Region() { Designation = "South Atlantic",     Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." };
                regions[7] = new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." };
                regions[8] = new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." };
    
                states[0]  = new Federation() { Abbreviation = "RI", Name = "Rhode Island",   Area =   1545, AreaSqrKms =    4002, AdmissionUnionOrder = 13, Capital = "Providence",     Region = regions[2] };
                states[1]  = new Federation() { Abbreviation = "OH", Name = "Ohio",           Area =  44828, AreaSqrKms =  116103, AdmissionUnionOrder = 17, Capital = "Columbus",       Region = regions[0] };
                states[2]  = new Federation() { Abbreviation = "KY", Name = "Kentucky",       Area =  40411, AreaSqrKms =  104665, AdmissionUnionOrder = 15, Capital = "Frankfort",      Region = regions[1] };
                states[3]  = new Federation() { Abbreviation = "IA", Name = "Iowa",           Area =  56276, AreaSqrKms =  145754, AdmissionUnionOrder = 29, Capital = "Des Moines",     Region = regions[7] };
                states[4]  = new Federation() { Abbreviation = "WI", Name = "Wisconsin",      Area =  65503, AreaSqrKms =  169653, AdmissionUnionOrder = 30, Capital = "Madison",        Region = regions[0] };
                states[5]  = new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = regions[2] };
                states[6]  = new Federation() { Abbreviation = "ID", Name = "Idaho",          Area =  83574, AreaSqrKms =  216456, AdmissionUnionOrder = 43, Capital = "Boise",          Region = regions[4] };
                states[7]  = new Federation() { Abbreviation = "ME", Name = "Maine",          Area =  35387, AreaSqrKms =   91653, AdmissionUnionOrder = 23, Capital = "Augusta",        Region = regions[2] };
                states[8]  = new Federation() { Abbreviation = "OR", Name = "Oregon",         Area =  98386, AreaSqrKms =  254819, AdmissionUnionOrder = 33, Capital = "Salem",          Region = regions[5] };
                states[9]  = new Federation() { Abbreviation = "ND", Name = "North Dakota",   Area =  70704, AreaSqrKms =  183123, AdmissionUnionOrder = 39, Capital = "Bismarck",       Region = regions[7] };
                states[10] = new Federation() { Abbreviation = "IN", Name = "Indiana",        Area =  36420, AreaSqrKms =   94328, AdmissionUnionOrder = 19, Capital = "Indianapolis",   Region = regions[0] };
                states[11] = new Federation() { Abbreviation = "MS", Name = "Mississippi",    Area =  48434, AreaSqrKms =  125443, AdmissionUnionOrder = 20, Capital = "Jackson",        Region = regions[1] };
                states[12] = new Federation() { Abbreviation = "TX", Name = "Texas",          Area = 268601, AreaSqrKms =  695676, AdmissionUnionOrder = 28, Capital = "Austin",         Region = regions[8] };
                states[13] = new Federation() { Abbreviation = "MT", Name = "Montana",        Area = 147046, AreaSqrKms =  380850, AdmissionUnionOrder = 41, Capital = "Helena",         Region = regions[4] };
                states[14] = new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53821, AreaSqrKms =  139397, AdmissionUnionOrder = 12, Capital = "Raleigh",        Region = regions[6] };
                states[15] = new Federation() { Abbreviation = "TN", Name = "Tennessee",      Area =  42146, AreaSqrKms =  109158, AdmissionUnionOrder = 16, Capital = "Nashville",      Region = regions[1] };
                states[16] = new Federation() { Abbreviation = "NE", Name = "Nebraska",       Area =  77358, AreaSqrKms =  200358, AdmissionUnionOrder = 37, Capital = "Lincoln",        Region = regions[7] };
                states[17] = new Federation() { Abbreviation = "IL", Name = "Illinois",       Area =  57918, AreaSqrKms =  150007, AdmissionUnionOrder = 21, Capital = "Springfield",    Region = regions[0] };
                states[18] = new Federation() { Abbreviation = "KS", Name = "Kansas",         Area =  82282, AreaSqrKms =  213110, AdmissionUnionOrder = 34, Capital = "Topeka",         Region = regions[7] };
                states[19] = new Federation() { Abbreviation = "NH", Name = "New Hampshire",  Area =   9351, AreaSqrKms =   24219, AdmissionUnionOrder =  9, Capital = "Concord",        Region = regions[2] };
                states[20] = new Federation() { Abbreviation = "DE", Name = "Delaware",       Area =   2489, AreaSqrKms =    6447, AdmissionUnionOrder =  1, Capital = "Dover",          Region = regions[6] };
                states[21] = new Federation() { Abbreviation = "NJ", Name = "New Jersey",     Area =   8722, AreaSqrKms =   22590, AdmissionUnionOrder =  3, Capital = "Trenton",        Region = regions[3] };
                states[22] = new Federation() { Abbreviation = "AK", Name = "Alaska",         Area = 656424, AreaSqrKms = 1700139, AdmissionUnionOrder = 49, Capital = "Juneau",         Region = regions[5] };
                states[23] = new Federation() { Abbreviation = "NM", Name = "New Mexico",     Area = 121598, AreaSqrKms =  314939, AdmissionUnionOrder = 47, Capital = "Santa Fe",       Region = regions[4] };
                states[24] = new Federation() { Abbreviation = "NY", Name = "New York",       Area =  54475, AreaSqrKms =  141089, AdmissionUnionOrder = 11, Capital = "Albany",         Region = regions[3] };
                states[25] = new Federation() { Abbreviation = "CA", Name = "California",     Area = 163707, AreaSqrKms =  424002, AdmissionUnionOrder = 31, Capital = "Sacramento",     Region = regions[5] };
                states[26] = new Federation() { Abbreviation = "MO", Name = "Missouri",       Area =  69709, AreaSqrKms =  180546, AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = regions[7] };
                states[27] = new Federation() { Abbreviation = "OK", Name = "Oklahoma",       Area =  69903, AreaSqrKms =  181049, AdmissionUnionOrder = 46, Capital = "Oklahoma City",  Region = regions[8] };
                states[28] = new Federation() { Abbreviation = "PA", Name = "Pennsylvania",   Area =  46058, AreaSqrKms =  119291, AdmissionUnionOrder =  2, Capital = "Harrisburg",     Region = regions[3] };
                states[29] = new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32007, AreaSqrKms =   82898, AdmissionUnionOrder =  8, Capital = "Columbia",       Region = regions[6] };
    
                lvwStates.Items.Clear();
                ListViewItem lviState = null;
    
                for (int counter = 0; counter <= states.Length - 1; counter++)
                {
                    lviState = new ListViewItem((counter + 1).ToString());
    
                    lviState.SubItems.Add(states[counter].Abbreviation);
                    lviState.SubItems.Add(states[counter].StateName);
                    lviState.SubItems.Add(states[counter].AreaSqrMiles.ToString());
                    lviState.SubItems.Add(states[counter].AreaSqrKms.ToString());
                    lviState.SubItems.Add(states[counter].AdmissionUnionOrder.ToString());
                    lviState.SubItems.Add(states[counter].Capital);
                    lviState.SubItems.Add(states[counter].Region.Designation);
    
                    lvwStates.Items.Add(lviState);
                }
            }
        }
    }
  27. To execute, on the main menu, click Debug -> Start Without Debugging:

    Looping Through an Arrray of Objects

  28. Close the form and return to your programming environment

Resizing an Array

By definition, an array is a fixed list. This means that, when creating an array, you specify the number of its elements, then you start adding values or objects to the array, but you cannot add items beyond the specified number. Sometimes in the real world, you may want to add items to an array without having to recreate the array. To assist you with this operation, the Array class includes a static method named Resize.

The Array.Resize() method takes two arguments. The first argument is passed by reference and is the name of the array you want to resize. The second argument is a constant integer that is the new size of the array. If the new size is lower than the length of the original array, a new array is created with that new size. This means that, to increase the size of an array, you should pass the second argument as the size of the orginal array + the number of new items you want to add.

Practical LearningPractical Learning: Resizing an Array

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace CountriesStatistics7
    {
        public partial class Form1 : Form
        {
            Federation[] states = new Federation[30];
            Region[] regions = new Region[9];
    
            public Form1()
            {
                InitializeComponent();
    
                Display();
            }
    
            void Display()
            {
                regions[0] = new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." };
                regions[1] = new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." };
                regions[2] = new Region() { Designation = "New England",        Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." };
                regions[3] = new Region() { Designation = "Mid-Atlantic",       Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." };
                regions[4] = new Region() { Designation = "Mountain",           Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." };
                regions[5] = new Region() { Designation = "Pacific",            Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." };
                regions[6] = new Region() { Designation = "South Atlantic",     Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." };
                regions[7] = new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." };
                regions[8] = new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." };
    
                states[0]  = new Federation() { Abbreviation = "RI", Name = "Rhode Island",   Area =   1545, AreaSqrKms =    4002, AdmissionUnionOrder = 13, Capital = "Providence",     Region = regions[2] };
                states[1]  = new Federation() { Abbreviation = "OH", Name = "Ohio",           Area =  44828, AreaSqrKms =  116103, AdmissionUnionOrder = 17, Capital = "Columbus",       Region = regions[0] };
                states[2]  = new Federation() { Abbreviation = "KY", Name = "Kentucky",       Area =  40411, AreaSqrKms =  104665, AdmissionUnionOrder = 15, Capital = "Frankfort",      Region = regions[1] };
                states[3]  = new Federation() { Abbreviation = "IA", Name = "Iowa",           Area =  56276, AreaSqrKms =  145754, AdmissionUnionOrder = 29, Capital = "Des Moines",     Region = regions[7] };
                states[4]  = new Federation() { Abbreviation = "WI", Name = "Wisconsin",      Area =  65503, AreaSqrKms =  169653, AdmissionUnionOrder = 30, Capital = "Madison",        Region = regions[0] };
                states[5]  = new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = regions[2] };
                states[6]  = new Federation() { Abbreviation = "ID", Name = "Idaho",          Area =  83574, AreaSqrKms =  216456, AdmissionUnionOrder = 43, Capital = "Boise",          Region = regions[4] };
                states[7]  = new Federation() { Abbreviation = "ME", Name = "Maine",          Area =  35387, AreaSqrKms =   91653, AdmissionUnionOrder = 23, Capital = "Augusta",        Region = regions[2] };
                states[8]  = new Federation() { Abbreviation = "OR", Name = "Oregon",         Area =  98386, AreaSqrKms =  254819, AdmissionUnionOrder = 33, Capital = "Salem",          Region = regions[5] };
                states[9]  = new Federation() { Abbreviation = "ND", Name = "North Dakota",   Area =  70704, AreaSqrKms =  183123, AdmissionUnionOrder = 39, Capital = "Bismarck",       Region = regions[7] };
                states[10] = new Federation() { Abbreviation = "IN", Name = "Indiana",        Area =  36420, AreaSqrKms =   94328, AdmissionUnionOrder = 19, Capital = "Indianapolis",   Region = regions[0] };
                states[11] = new Federation() { Abbreviation = "MS", Name = "Mississippi",    Area =  48434, AreaSqrKms =  125443, AdmissionUnionOrder = 20, Capital = "Jackson",        Region = regions[1] };
                states[12] = new Federation() { Abbreviation = "TX", Name = "Texas",          Area = 268601, AreaSqrKms =  695676, AdmissionUnionOrder = 28, Capital = "Austin",         Region = regions[8] };
                states[13] = new Federation() { Abbreviation = "MT", Name = "Montana",        Area = 147046, AreaSqrKms =  380850, AdmissionUnionOrder = 41, Capital = "Helena",         Region = regions[4] };
                states[14] = new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53821, AreaSqrKms =  139397, AdmissionUnionOrder = 12, Capital = "Raleigh",        Region = regions[6] };
                states[15] = new Federation() { Abbreviation = "TN", Name = "Tennessee",      Area =  42146, AreaSqrKms =  109158, AdmissionUnionOrder = 16, Capital = "Nashville",      Region = regions[1] };
                states[16] = new Federation() { Abbreviation = "NE", Name = "Nebraska",       Area =  77358, AreaSqrKms =  200358, AdmissionUnionOrder = 37, Capital = "Lincoln",        Region = regions[7] };
                states[17] = new Federation() { Abbreviation = "IL", Name = "Illinois",       Area =  57918, AreaSqrKms =  150007, AdmissionUnionOrder = 21, Capital = "Springfield",    Region = regions[0] };
                states[18] = new Federation() { Abbreviation = "KS", Name = "Kansas",         Area =  82282, AreaSqrKms =  213110, AdmissionUnionOrder = 34, Capital = "Topeka",         Region = regions[7] };
                states[19] = new Federation() { Abbreviation = "NH", Name = "New Hampshire",  Area =   9351, AreaSqrKms =   24219, AdmissionUnionOrder =  9, Capital = "Concord",        Region = regions[2] };
                states[20] = new Federation() { Abbreviation = "DE", Name = "Delaware",       Area =   2489, AreaSqrKms =    6447, AdmissionUnionOrder =  1, Capital = "Dover",          Region = regions[6] };
                states[21] = new Federation() { Abbreviation = "NJ", Name = "New Jersey",     Area =   8722, AreaSqrKms =   22590, AdmissionUnionOrder =  3, Capital = "Trenton",        Region = regions[3] };
                states[22] = new Federation() { Abbreviation = "AK", Name = "Alaska",         Area = 656424, AreaSqrKms = 1700139, AdmissionUnionOrder = 49, Capital = "Juneau",         Region = regions[5] };
                states[23] = new Federation() { Abbreviation = "NM", Name = "New Mexico",     Area = 121598, AreaSqrKms =  314939, AdmissionUnionOrder = 47, Capital = "Santa Fe",       Region = regions[4] };
                states[24] = new Federation() { Abbreviation = "NY", Name = "New York",       Area =  54475, AreaSqrKms =  141089, AdmissionUnionOrder = 11, Capital = "Albany",         Region = regions[3] };
                states[25] = new Federation() { Abbreviation = "CA", Name = "California",     Area = 163707, AreaSqrKms =  424002, AdmissionUnionOrder = 31, Capital = "Sacramento",     Region = regions[5] };
                states[26] = new Federation() { Abbreviation = "MO", Name = "Missouri",       Area =  69709, AreaSqrKms =  180546, AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = regions[7] };
                states[27] = new Federation() { Abbreviation = "OK", Name = "Oklahoma",       Area =  69903, AreaSqrKms =  181049, AdmissionUnionOrder = 46, Capital = "Oklahoma City",  Region = regions[8] };
                states[28] = new Federation() { Abbreviation = "PA", Name = "Pennsylvania",   Area =  46058, AreaSqrKms =  119291, AdmissionUnionOrder =  2, Capital = "Harrisburg",     Region = regions[3] };
                states[29] = new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32007, AreaSqrKms =   82898, AdmissionUnionOrder =  8, Capital = "Columbia",       Region = regions[6] };
    
                Array.Resize(ref states, states.Length + 10);
    
                states[30] = new Federation() { Abbreviation = "WY", Name = "Wyoming",        Area =  97818, AreaSqrKms =  253349, AdmissionUnionOrder = 44, Capital = "Cheyenne",       Region = regions[4] };
                states[31] = new Federation() { Abbreviation = "SD", Name = "South Dakota",   Area =  77122, AreaSqrKms =  199745, AdmissionUnionOrder = 40, Capital = "Pierre",         Region = regions[7] };
                states[32] = new Federation() { Abbreviation = "UT", Name = "Utah",           Area =  84904, AreaSqrKms =  219902, AdmissionUnionOrder = 45, Capital = "Salt Lake City", Region = regions[4] };
                states[33] = new Federation() { Abbreviation = "AL", Name = "Alabama",        Area =  52423, AreaSqrKms =  135775, AdmissionUnionOrder = 22, Capital = "Montgomery",     Region = regions[1] };
                states[34] = new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = regions[2] };
                states[35] = new Federation() { Abbreviation = "AR", Name = "Arkansas",       Area =  53182, AreaSqrKms =  137742, AdmissionUnionOrder = 25, Capital = "Little Rock",    Region = regions[8] };
                states[36] = new Federation() { Abbreviation = "WA", Name = "Washington",     Area =  71303, AreaSqrKms =  184674, AdmissionUnionOrder = 42, Capital = "Olympia",        Region = regions[5] };
                states[37] = new Federation() { Abbreviation = "AZ", Name = "Arizona",        Area = 114006, AreaSqrKms =  295276, AdmissionUnionOrder = 48, Capital = "Phoenix",        Region = regions[4] };
                states[38] = new Federation() { Abbreviation = "WV", Name = "West Virginia",  Area =  24231, AreaSqrKms =   62759, AdmissionUnionOrder = 35, Capital = "Charleston",     Region = regions[6] };
                states[39] = new Federation() { Abbreviation = "LA", Name = "Louisiana",      Area =  51844, AreaSqrKms =  134275, AdmissionUnionOrder = 18, Capital = "Baton Rouge",    Region = regions[8] };
    
                lvwStates.Items.Clear();
                ListViewItem lviState = null;
    
                for (int counter = 0; counter <= states.Length - 1; counter++)
                {
                    lviState = new ListViewItem((counter + 1).ToString());
    
                    lviState.SubItems.Add(states[counter].Abbreviation);
                    lviState.SubItems.Add(states[counter].StateName);
                    lviState.SubItems.Add(states[counter].AreaSqrMiles.ToString());
                    lviState.SubItems.Add(states[counter].AreaSqrKms.ToString());
                    lviState.SubItems.Add(states[counter].AdmissionUnionOrder.ToString());
                    lviState.SubItems.Add(states[counter].Capital);
                    lviState.SubItems.Add(states[counter].Region.Designation);
    
                    lvwStates.Items.Add(lviState);
                }
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    A Simple Form

  3. Close the form and return to your programming environment

Copying an Array

Copying an array consists of assigning its values or objects to another array. To support this operation, the Array class provides various methods. The classic technique uses a method named Copy. It is overloaded in four versions for different scenarios. Two syntaxes of the method are:

public static void Copy (Array sourceArray, Array destinationArray, int length);
public static void Copy (Array sourceArray, Array destinationArray, long length);

These versions take three arguments. The first argument is the source array. The second argument is the destination array. The last argument is the number of items that will be copied.

Practical LearningPractical Learning: Copying an Array

  1. Change the code as follows:
    using System;
    using System.Windows.Forms;
    
    namespace CountriesStatistics7
    {
        public partial class Form1 : Form
        {
            Federation[] states = new Federation[30];
            Region[] regions = new Region[9];
    
            public Form1()
            {
                InitializeComponent();
    
                Display();
            }
    
            void Display()
            {
                regions[0] = new Region() { Designation = "East North Central", Description = "The East North Central region includes the states around the Great Lakes." };
                regions[1] = new Region() { Designation = "East South Central", Description = "The East South Central portion is one of the regions designated as the South." };
                regions[2] = new Region() { Designation = "New England",        Description = "New England is the group of states in the North-East region. It is delimited in the North and North-East by Canada, in the East by the Atlantic Ocean, and in the South and West by the New York state." };
                regions[3] = new Region() { Designation = "Mid-Atlantic",       Description = "Mid-Atlantic is a region situated in the south of New England. Mid-Atlantic is one of the regions defined by the Census bureau for statistical purposes." };
                regions[4] = new Region() { Designation = "Mountain",           Description = "Like the name suggests, the Mountain region covers states known for their mountaneous characteristics. They are also covered by desertic areas." };
                regions[5] = new Region() { Designation = "Pacific",            Description = "The Pacific region covers the costal western states plus the two non-continental states of Alaska and the Hawaiian islands. All states in this region have a coast on the Pacific Ocean." };
                regions[6] = new Region() { Designation = "South Atlantic",     Description = "The South Atlantic region includes the states in the South-East part but also counts the Disctrict of Columbia." };
                regions[7] = new Region() { Designation = "West North Central", Description = "The West North Central region includes the states in the Great Planes area. This reqion is divided from the East North Central part by the Mississippi River. This region is characterized by vast agricultural farms and high employment." };
                regions[8] = new Region() { Designation = "West South Central", Description = "The West South Central part is one of the regions with (only) four states. The imposing Texas state is both the largest and the most populous state in the region." };
    
                states[0]  = new Federation() { Abbreviation = "RI", Name = "Rhode Island",   Area =   1545, AreaSqrKms =    4002, AdmissionUnionOrder = 13, Capital = "Providence",     Region = regions[2] };
                states[1]  = new Federation() { Abbreviation = "OH", Name = "Ohio",           Area =  44828, AreaSqrKms =  116103, AdmissionUnionOrder = 17, Capital = "Columbus",       Region = regions[0] };
                states[2]  = new Federation() { Abbreviation = "KY", Name = "Kentucky",       Area =  40411, AreaSqrKms =  104665, AdmissionUnionOrder = 15, Capital = "Frankfort",      Region = regions[1] };
                states[3]  = new Federation() { Abbreviation = "IA", Name = "Iowa",           Area =  56276, AreaSqrKms =  145754, AdmissionUnionOrder = 29, Capital = "Des Moines",     Region = regions[7] };
                states[4]  = new Federation() { Abbreviation = "WI", Name = "Wisconsin",      Area =  65503, AreaSqrKms =  169653, AdmissionUnionOrder = 30, Capital = "Madison",        Region = regions[0] };
                states[5]  = new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = regions[2] };
                states[6]  = new Federation() { Abbreviation = "ID", Name = "Idaho",          Area =  83574, AreaSqrKms =  216456, AdmissionUnionOrder = 43, Capital = "Boise",          Region = regions[4] };
                states[7]  = new Federation() { Abbreviation = "ME", Name = "Maine",          Area =  35387, AreaSqrKms =   91653, AdmissionUnionOrder = 23, Capital = "Augusta",        Region = regions[2] };
                states[8]  = new Federation() { Abbreviation = "OR", Name = "Oregon",         Area =  98386, AreaSqrKms =  254819, AdmissionUnionOrder = 33, Capital = "Salem",          Region = regions[5] };
                states[9]  = new Federation() { Abbreviation = "ND", Name = "North Dakota",   Area =  70704, AreaSqrKms =  183123, AdmissionUnionOrder = 39, Capital = "Bismarck",       Region = regions[7] };
                states[10] = new Federation() { Abbreviation = "IN", Name = "Indiana",        Area =  36420, AreaSqrKms =   94328, AdmissionUnionOrder = 19, Capital = "Indianapolis",   Region = regions[0] };
                states[11] = new Federation() { Abbreviation = "MS", Name = "Mississippi",    Area =  48434, AreaSqrKms =  125443, AdmissionUnionOrder = 20, Capital = "Jackson",        Region = regions[1] };
                states[12] = new Federation() { Abbreviation = "TX", Name = "Texas",          Area = 268601, AreaSqrKms =  695676, AdmissionUnionOrder = 28, Capital = "Austin",         Region = regions[8] };
                states[13] = new Federation() { Abbreviation = "MT", Name = "Montana",        Area = 147046, AreaSqrKms =  380850, AdmissionUnionOrder = 41, Capital = "Helena",         Region = regions[4] };
                states[14] = new Federation() { Abbreviation = "NC", Name = "North Carolina", Area =  53821, AreaSqrKms =  139397, AdmissionUnionOrder = 12, Capital = "Raleigh",        Region = regions[6] };
                states[15] = new Federation() { Abbreviation = "TN", Name = "Tennessee",      Area =  42146, AreaSqrKms =  109158, AdmissionUnionOrder = 16, Capital = "Nashville",      Region = regions[1] };
                states[16] = new Federation() { Abbreviation = "NE", Name = "Nebraska",       Area =  77358, AreaSqrKms =  200358, AdmissionUnionOrder = 37, Capital = "Lincoln",        Region = regions[7] };
                states[17] = new Federation() { Abbreviation = "IL", Name = "Illinois",       Area =  57918, AreaSqrKms =  150007, AdmissionUnionOrder = 21, Capital = "Springfield",    Region = regions[0] };
                states[18] = new Federation() { Abbreviation = "KS", Name = "Kansas",         Area =  82282, AreaSqrKms =  213110, AdmissionUnionOrder = 34, Capital = "Topeka",         Region = regions[7] };
                states[19] = new Federation() { Abbreviation = "NH", Name = "New Hampshire",  Area =   9351, AreaSqrKms =   24219, AdmissionUnionOrder =  9, Capital = "Concord",        Region = regions[2] };
                states[20] = new Federation() { Abbreviation = "DE", Name = "Delaware",       Area =   2489, AreaSqrKms =    6447, AdmissionUnionOrder =  1, Capital = "Dover",          Region = regions[6] };
                states[21] = new Federation() { Abbreviation = "NJ", Name = "New Jersey",     Area =   8722, AreaSqrKms =   22590, AdmissionUnionOrder =  3, Capital = "Trenton",        Region = regions[3] };
                states[22] = new Federation() { Abbreviation = "AK", Name = "Alaska",         Area = 656424, AreaSqrKms = 1700139, AdmissionUnionOrder = 49, Capital = "Juneau",         Region = regions[5] };
                states[23] = new Federation() { Abbreviation = "NM", Name = "New Mexico",     Area = 121598, AreaSqrKms =  314939, AdmissionUnionOrder = 47, Capital = "Santa Fe",       Region = regions[4] };
                states[24] = new Federation() { Abbreviation = "NY", Name = "New York",       Area =  54475, AreaSqrKms =  141089, AdmissionUnionOrder = 11, Capital = "Albany",         Region = regions[3] };
                states[25] = new Federation() { Abbreviation = "CA", Name = "California",     Area = 163707, AreaSqrKms =  424002, AdmissionUnionOrder = 31, Capital = "Sacramento",     Region = regions[5] };
                states[26] = new Federation() { Abbreviation = "MO", Name = "Missouri",       Area =  69709, AreaSqrKms =  180546, AdmissionUnionOrder = 24, Capital = "Jefferson City", Region = regions[7] };
                states[27] = new Federation() { Abbreviation = "OK", Name = "Oklahoma",       Area =  69903, AreaSqrKms =  181049, AdmissionUnionOrder = 46, Capital = "Oklahoma City",  Region = regions[8] };
                states[28] = new Federation() { Abbreviation = "PA", Name = "Pennsylvania",   Area =  46058, AreaSqrKms =  119291, AdmissionUnionOrder =  2, Capital = "Harrisburg",     Region = regions[3] };
                states[29] = new Federation() { Abbreviation = "SC", Name = "South Carolina", Area =  32007, AreaSqrKms =   82898, AdmissionUnionOrder =  8, Capital = "Columbia",       Region = regions[6] };
    
                Array.Resize(ref states, states.Length + 10);
    
                states[30] = new Federation() { Abbreviation = "WY", Name = "Wyoming",        Area =  97818, AreaSqrKms =  253349, AdmissionUnionOrder = 44, Capital = "Cheyenne",       Region = regions[4] };
                states[31] = new Federation() { Abbreviation = "SD", Name = "South Dakota",   Area =  77122, AreaSqrKms =  199745, AdmissionUnionOrder = 40, Capital = "Pierre",         Region = regions[7] };
                states[32] = new Federation() { Abbreviation = "UT", Name = "Utah",           Area =  84904, AreaSqrKms =  219902, AdmissionUnionOrder = 45, Capital = "Salt Lake City", Region = regions[4] };
                states[33] = new Federation() { Abbreviation = "AL", Name = "Alabama",        Area =  52423, AreaSqrKms =  135775, AdmissionUnionOrder = 22, Capital = "Montgomery",     Region = regions[1] };
                states[34] = new Federation() { Abbreviation = "VT", Name = "Vermont",        Area =   9615, AreaSqrKms =   24903, AdmissionUnionOrder = 14, Capital = "Montpelier",     Region = regions[2] };
                states[35] = new Federation() { Abbreviation = "AR", Name = "Arkansas",       Area =  53182, AreaSqrKms =  137742, AdmissionUnionOrder = 25, Capital = "Little Rock",    Region = regions[8] };
                states[36] = new Federation() { Abbreviation = "WA", Name = "Washington",     Area =  71303, AreaSqrKms =  184674, AdmissionUnionOrder = 42, Capital = "Olympia",        Region = regions[5] };
                states[37] = new Federation() { Abbreviation = "AZ", Name = "Arizona",        Area = 114006, AreaSqrKms =  295276, AdmissionUnionOrder = 48, Capital = "Phoenix",        Region = regions[4] };
                states[38] = new Federation() { Abbreviation = "WV", Name = "West Virginia",  Area =  24231, AreaSqrKms =   62759, AdmissionUnionOrder = 35, Capital = "Charleston",     Region = regions[6] };
                states[39] = new Federation() { Abbreviation = "LA", Name = "Louisiana",      Area =  51844, AreaSqrKms =  134275, AdmissionUnionOrder = 18, Capital = "Baton Rouge",    Region = regions[8] };
    
                Federation[] temporary = new Federation[states.Length + 10];
                Array.Copy(states, temporary, states.Length);
                states = temporary;
    
                states[40] = new Federation() { Abbreviation = "MA", Name = "Massachusetts",  Area =  10555, AreaSqrKms =   27337, AdmissionUnionOrder =  6, Capital = "Boston",         Region = regions[2] };
                states[41] = new Federation() { Abbreviation = "FL", Name = "Florida",        Area =  65758, AreaSqrKms =  170313, AdmissionUnionOrder = 27, Capital = "Tallahassee",    Region = regions[6] };
                states[42] = new Federation() { Abbreviation = "GA", Name = "Georgia",        Area =  59441, AreaSqrKms =  153953, AdmissionUnionOrder =  4, Capital = "Atlanta",        Region = regions[6] };
                states[43] = new Federation() { Abbreviation = "HI", Name = "Hawaii",         Area =  10932, AreaSqrKms =   28313, AdmissionUnionOrder = 50, Capital = "Honolulu",       Region = regions[5] };
                states[44] = new Federation() { Abbreviation = "MD", Name = "Maryland",       Area =  12407, AreaSqrKms =   32135, AdmissionUnionOrder =  7, Capital = "Annapolis",      Region = regions[6] };
                states[45] = new Federation() { Abbreviation = "CO", Name = "Colorado",       Area = 104100, AreaSqrKms =  269620, AdmissionUnionOrder = 38, Capital = "Denver",         Region = regions[4] };
                states[46] = new Federation() { Abbreviation = "MI", Name = "Michigan",       Area =  98810, AreaSqrKms =  250738, AdmissionUnionOrder = 26, Capital = "Lansing",        Region = regions[0] };
                states[47] = new Federation() { Abbreviation = "MN", Name = "Minnesota",      Area =  86943, AreaSqrKms =  225182, AdmissionUnionOrder = 32, Capital = "Saint Paul",     Region = regions[7] };
                states[48] = new Federation() { Abbreviation = "CT", Name = "Connecticut",    Area =   5544, AreaSqrKms =   14358, AdmissionUnionOrder =  5, Capital = "Hartford",       Region = regions[3] };
                states[49] = new Federation() { Abbreviation = "NV", Name = "Nevada",         Area = 110567, AreaSqrKms =  286368, AdmissionUnionOrder = 36, Capital = "Frankfort",      Region = regions[4] };
    
                lvwStates.Items.Clear();
                ListViewItem lviState = null;
    
                for (int counter = 0; counter <= states.Length - 1; counter++)
                {
                    lviState = new ListViewItem((counter + 1).ToString());
    
                    lviState.SubItems.Add(states[counter].Abbreviation);
                    lviState.SubItems.Add(states[counter].StateName);
                    lviState.SubItems.Add(states[counter].AreaSqrMiles.ToString());
                    lviState.SubItems.Add(states[counter].AreaSqrKms.ToString());
                    lviState.SubItems.Add(states[counter].AdmissionUnionOrder.ToString());
                    lviState.SubItems.Add(states[counter].Capital);
                    lviState.SubItems.Add(states[counter].Region.Designation);
    
                    lvwStates.Items.Add(lviState);
                }
            }
        }
    }
  2. To execute, on the main menu, click Debug -> Start Without Debugging:

    Copying an Array

  3. Close the form and return to your programming environment

Finding an Item in an Array

The Array class provides various means of looking for, or locating, an element in an array.

To support binary search, the Array class is equipped with a method named BinarySearch that is overloaded in 8 versions. One of the versions uses the following syntax:

public static int BinarySearch(Array array, object value);

Before calling this method, you can sort the array. Here is an example of calling it:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        int index = Array.BinarySearch(numbers, 525);

        WriteLine("The position of 525 is {0}", index);
        WriteLine("==============================");

        Array.Sort(numbers);

        WriteLine("Sorted List");
        WriteLine("-------------------");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        index = Array.BinarySearch(numbers, 525);

        WriteLine("The position of 525 is {0}", index);
        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
The position of 525 is -3
==============================
Sorted List
-------------------
Number: 0.70257
Number: 6.48
Number: 28.07
Number: 314.905
Number: 574.9
Number: 7628.937
Number: 80458.01
Number: 293749.064
The position of 525 is -5
=================================
Press any key to continue . . .

Locating the Index of an Element

One of the most routine operations you can perform on an array is to find out whether it contains this or that value. For example, if the array contains a certain member, you may want to retrieve the index of that member. To assist you with this, the Array class is equipped with a method named IndexOf() method that comes in various versions. To apply it on the type of array we have used so far, you can use the following syntax:

public static int IndexOf(Array array, object value);

This method visits each member of the array, looking for the value. Once it finds value in the array, it stops and returns the index where the first occurrence of value was found. If the Array.IndexOf() method finds the value in the array, it returns its position. Here is an example of calling it:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        int index   = Array.IndexOf(numbers, 293749.064);

        WriteLine("The index of 293749.064 is {0}", index);
        WriteLine("==============================");

        Array.Sort(numbers);

        WriteLine("Sorted List");
        WriteLine("-------------------");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        index = Array.IndexOf(numbers, 293749.064);

        WriteLine(string.Format("The index of 293749.064 is {0}", index));
        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
The index of 293749.064 is 3
==============================
Sorted List
-------------------
Number: 0.70257
Number: 6.48
Number: 28.07
Number: 314.905
Number: 574.9
Number: 7628.937
Number: 80458.01
Number: 293749.064
The index of 293749.064 is 7
=================================
Press any key to continue . . .

If the item is not found in the array, the method may return -1.

The IndexOf() method actually looks for the first occurrence of an item in an array. If you prefer to get the last occurrence of that item in the array, you can call the Array.LastIndexOf() method. It also is overloaded in three versions.

Sorting an Array

When accessing the members of an array, you may want them to be arranged in alphabetical, numerical, or chronological order. To assist you with re-arranging the elements in an array, the Array class is equipped with a method named Sort that is overloaded with as many versions as you can possibly need.

To arrange an array, you can call the following version of the Array.Sort() method:

public static void Sort(Array array);

This is a static method that takes as argument the name of the array you want to re-arrange. If your array is a list of primitive values, the sorting operation is automatic. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        WriteLine("=====================");

        Array.Sort(numbers);

        WriteLine("Sorted List");
        WriteLine("-------------------");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
=====================
Sorted List
-------------------
Number: 0.70257
Number: 6.48
Number: 28.07
Number: 314.905
Number: 574.9
Number: 7628.937
Number: 80458.01
Number: 293749.064
=================================
Press any key to continue . . .

Notice that the numbers are arranged in in ascending order. In the same way, if the array is made of strings, you can call the Array.Sort() method to arrange the list in alphabetical order. If the array is made of dates, you can arrange them in chronological order.

If your array is a list of objects, the class that constitutes the array must implement the IComparable interface that we introduced already.

Reversing an Array

When you display the values of an array, they appear in the order they were added in the list. If you want, you can display the list from the last added item to the first added. To assist you with this operation, the Array class provides a method named Reverse. Its syntax is:

public static void Reverse(Array array);

This method neither arranges an array nor reverses a sorted array, It simply reverses whatever order the array holds. Here is an example of calling this method:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        int index   = Array.IndexOf(numbers, 574.9);

        WriteLine("The index of 574.9 is {0}", index);
        WriteLine("==============================");

        Array.Reverse(numbers);

        WriteLine("Reversed List");
        WriteLine("-------------------");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        index = Array.IndexOf(numbers, 574.9);

        WriteLine(string.Format("The index of 574.9 is {0}", index));
        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
The index of 574.9 is 2
==============================
Reversed List
-------------------
Number: 28.07
Number: 80458.01
Number: 314.905
Number: 0.70257
Number: 293749.064
Number: 574.9
Number: 6.48
Number: 7628.937
The index of 574.9 is 5
=================================
Press any key to continue . . .

In the same way, you can reverse

Removing Items from an Array

Deleting an Item From an Array

Deleting an item from an array consists of removing it from the list. The Array class allows you to delete one element or a range of items from an array. To support these operations, the class is equipped with a static method named Clear. Its syntax is:

public static void Clear(Array array, int index, int length);

The first argument of this method is the name of the array on which the operation is performed. The second argument is the index of the item where the deletion will occur or start. If that second index exists in the array, the third argument specifies the number of items to remove. If an item is deleted, it receives a default value. For example, if it is a number, it gets a 0 value.

If you want to delete just one item, provide its index as the second argument and 1 as the third. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        WriteLine("==============================");

        Array.Clear(numbers, 2, 1);

        WriteLine("Modified List of Items");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
==============================
Modified List of Items
Number: 7628.937
Number: 6.48
Number: 0
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
=================================
Press any key to continue . . .

Deleting a Range of Items from an Array

To delete a range of items, pass the starting index as the second argument and pass the length of the range (the number of items to delete from the starting point) as the second argument. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        WriteLine("==============================");

        Array.Clear(numbers, 2, 3);

        WriteLine("Modified List of Items");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
==============================
Modified List of Items
Number: 7628.937
Number: 6.48
Number: 0
Number: 0
Number: 0
Number: 314.905
Number: 80458.01
Number: 28.07
=================================
Press any key to continue . . .

Clearing an Array

Clearing an array consists of deleting all of its elements and setting the count to 0. To do it, call the Array.Clear() method. Pass 0 as the second argument and the length of the array as the third argument. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        const int length = 8;

        double[] numbers = new double[length]
        {
            7628.937,     6.48,    574.9,  293749.064,
               0.70257, 314.905, 80458.01,     28.07
        };

        WriteLine("Original List");
        WriteLine("--------------------");

        foreach (var number in numbers)
            WriteLine("Number: {0}", number);
        
        WriteLine("==============================");

        Array.Clear(numbers, 0, numbers.Length);

        WriteLine("Modified List of Items");

        foreach (var number in numbers)
            WriteLine(string.Format("Number: {0}", number));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Original List
--------------------
Number: 7628.937
Number: 6.48
Number: 574.9
Number: 293749.064
Number: 0.70257
Number: 314.905
Number: 80458.01
Number: 28.07
==============================
Modified List of Items
Number: 0
Number: 0
Number: 0
Number: 0
Number: 0
Number: 0
Number: 0
Number: 0
=================================
Press any key to continue . . .

Multidimensional Arrays

Two-Dimensional Arrays

The Array class supports the creation of any of the types of arrays we saw in the previous lessons. We already know that a two-dimensional array was an array made of two lists:

public class Exercise
{
    public static int Main(string[] args)
    {
        var members = new string[List1Length, List2Length];
    }
}

To create such an array using the Array class, you can use the following version of the Array.CreateInstance() method:

public static Array CreateInstance(Type elementType, int length1, int length2)

The first argument is the type of array you want to create. The second argument is the length of the first list. The third argument is the length of the second list. Here are examples of using it:

public class Exercise
{
    public static int Main(string[] args)
    {
        Array numbers = Array.CreateInstance(typeof(double), 6, 3);
        var names = Array.CreateInstance(typeof(string), 2, 4);
        dynamic distances = Array.CreateInstance(typeof(string), 5, 17);
    }
}

To specify the values of a two-dimensional array, you can use the following version of the Array.SetValue() method:

public void SetValue(object value, int index1, int index2)

The first argument is the value you want to specify. The second argument is the index of the list. The second argument is the index of the element that is being added. Here is an example:

public class Exercise
{
    public static int Main(string[] args)
    {
        var members = Array.CreateInstance(typeof(string), 2, 4);
        
        members.SetValue("Celeste", 0, 0);    // 1st List - 1st Element
        members.SetValue("Mathurin", 0, 1);   // 1st List - 2nd Element
        members.SetValue("Alex", 0, 2);       // 1st List - 3rd Element
        members.SetValue("Germain",0, 3);     // 1st List - 4th Element
        
    	members.SetValue("Jeremy", 1, 0);     // 2nd List - 1st Element
        members.SetValue("Mathew", 1, 1);     // 1st List - 2nd Element
        members.SetValue("Anselme", 1, 2);    // 1st List - 3rd Element
        members.SetValue("Frederique", 1, 3); // 1st List - 4th Element
    }
}

Just as mentioned for the one-dimensional array, you can use the square brackets to create the array but call the SetValue() method to specify the value of each element.

To access a member of a two-dimensional array created with the Array.SetValue() method, you use the following version of the Array.GetValue() method:

public object GetValue(int index1, int index2)

This method takes two arguments. The first argument is the index of the list where the desired member resides. The second argument is the index of the element itself. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {

        var members = Array.CreateInstance(typeof(string), 2, 4);

        members.SetValue("Celeste", 0, 0);  // 1st List - 1st Element
        members.SetValue("Mathurin", 0, 1); // 1st List - 2nd Element
        members.SetValue("Alex", 0, 2);     // 1st List - 3rd Element
        members.SetValue("Germain", 0, 3);   // 1st List - 4th Element

        members.SetValue("Jeremy", 1, 0);   // 2nd List - 1st Element
        members.SetValue("Mathew", 1, 1);   // 1st List - 2nd Element
        members.SetValue("Anselme", 1, 2);  // 1st List - 3rd Element
        members.SetValue("Frederique", 1, 3);// 1st List - 4th Element

        WriteLine("Member: {0}", members.GetValue(0, 2));
        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Member: Alex
=================================
Press any key to continue . . .

To access each member of the list, you can use two for loops. Use the first loop to access each list. Nest a second loop to it to access each member. To get the dimension of the main list, you can call the Array.GetLength() method and specify its argument as 0. For the internal loop, pass 1 as the argument to the Array.GetLength() method. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var members = Array.CreateInstance(typeof(string), 2, 4);

        members.SetValue("Celeste", 0, 0);      // 1st List - 1st Element
        members.SetValue("Mathurin", 0, 1);     // 1st List - 2nd Element
        members.SetValue("Alex", 0, 2);         // 1st List - 3rd Element
        members.SetValue("Germain", 0, 3);      // 1st List - 4th Element

        members.SetValue("Jeremy", 1, 0);       // 2nd List - 1st Element
        members.SetValue("Mathew", 1, 1);       // 1st List - 2nd Element
        members.SetValue("Anselme", 1, 2);      // 1st List - 3rd Element
        members.SetValue("Frederique", 1, 3);   // 1st List - 4th Element

        for (int list = 0; list < members.GetLength(0); list++)
            for (int counter = 0; counter < members.GetLength(1); counter++)
                WriteLine("Member: {0}", members.GetValue(list, counter));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Member: Celeste
Member: Mathurin
Member: Alex
Member: Germain
Member: Jeremy
Member: Mathew
Member: Anselme
Member: Frederique
=================================
Press any key to continue . . .

You can also use a foreach operator to access each member of the array. When using it, there is no need for a counter. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        Array members = Array.CreateInstance(typeof(string), 2, 4);

        members.SetValue("Celeste", 0, 0);      // 1st List - 1st Element
        members.SetValue("Mathurin", 0, 1);     // 1st List - 2nd Element
        members.SetValue("Alex", 0, 2);         // 1st List - 3rd Element
        members.SetValue("Germain", 0, 3);      // 1st List - 4th Element

        members.SetValue("Jeremy", 1, 0);       // 2nd List - 1st Element
        members.SetValue("Mathew", 1, 1);       // 1st List - 2nd Element
        members.SetValue("Anselme", 1, 2);      // 1st List - 3rd Element
        members.SetValue("Frederique", 1, 3);   // 1st List - 4th Element

        foreach (var member in members)
            WriteLine("Member: {0}", member);

        WriteLine("=================================");
        return 0;
    }
}

Three-Dimensional Arrays

Instead of two dimensions, you may want to create a three-dimensional array. A 3-D array is an array that, if created with the square brackets, would use two commas. Here is an example:

public class Exercise
{
    public static int Main(string[] args)
    {
        double[,,] Number;
        
        return 0;
    }
}

To create such an array using the Array class, you can use the following version of its CreateInstance() method:

public static Array CreateInstance(Type elementType,
								   int length1,
								   int length2,
	 							   int length3)

Here is an example:

public class Exercise
{
    public static int Main(string[] args)
    {
        var number = Array.CreateInstance(typeof(double), 2, 3, 5);
        
        return 1000;
    }
}

To specify the value of each member of the three-dimensional array, you can call the following version of the Array.SetValue() method:

public void SetValue(Object value,
					 int index1,
					 int index2,
					 int index3)

Here is an example:

public class Exercise
{
    public static int Main(string[] args)
    {
        var number = Array.CreateInstance(typeof(double), 2, 3, 5);

        number.SetValue(  12.44, 0, 0, 0);
        number.SetValue( 525.38, 0, 0, 1);
        number.SetValue(  -6.28, 0, 0, 2);
        number.SetValue(2448.32, 0, 0, 3);
        number.SetValue( 632.04, 0, 0, 4);
        number.SetValue(-378.05, 0, 1, 0);
        number.SetValue(  48.14, 0, 1, 1);
        number.SetValue( 634.18, 0, 1, 2);
        number.SetValue( 762.48, 0, 1, 3);
        number.SetValue(  83.02, 0, 1, 4);
        number.SetValue(  64.92, 0, 2, 0);
        number.SetValue(  -7.44, 0, 2, 1);
        number.SetValue(  86.74, 0, 2, 2);
        number.SetValue(-534.60, 0, 2, 3);
        number.SetValue( 386.73, 0, 2, 4);
        number.SetValue(  48.02, 1, 0, 0);
        number.SetValue( 120.44, 1, 0, 1);
        number.SetValue(  38.62, 1, 0, 2);
        number.SetValue( 526.82, 1, 0, 3);
        number.SetValue(1704.62, 1, 0, 4);
        number.SetValue(  56.85, 1, 1, 0);
        number.SetValue(105.48,  1, 1, 1);
        number.SetValue( 363.31, 1, 1, 2);
        number.SetValue( 172.62, 1, 1, 3);
        number.SetValue( 128.48, 1, 1, 4);
        number.SetValue( 906.68, 1, 2, 0);
        number.SetValue(  47.12, 1, 2, 1);
        number.SetValue(-166.07, 1, 2, 2);
        number.SetValue(4444.26, 1, 2, 3);
        number.SetValue( 408.62, 1, 2, 4);
    }
}

To get the value of each member of the three-dimensional array, you can call the following version of the Array.GetValue() method:

public Object GetValue(int index1,
					   int index2,
					   int index3)

Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var number = Array.CreateInstance(typeof(double), 2, 3, 5);

        number.SetValue(  12.44, 0, 0, 0);
        number.SetValue( 525.38, 0, 0, 1);
        number.SetValue(  -6.28, 0, 0, 2);
        number.SetValue(2448.32, 0, 0, 3);
        number.SetValue( 632.04, 0, 0, 4);
        number.SetValue(-378.05, 0, 1, 0);
        number.SetValue(  48.14, 0, 1, 1);
        number.SetValue( 634.18, 0, 1, 2);
        number.SetValue( 762.48, 0, 1, 3);
        number.SetValue(  83.02, 0, 1, 4);
        number.SetValue(  64.92, 0, 2, 0);
        number.SetValue(  -7.44, 0, 2, 1);
        number.SetValue(  86.74, 0, 2, 2);
        number.SetValue(-534.60, 0, 2, 3);
        number.SetValue( 386.73, 0, 2, 4);
        number.SetValue(  48.02, 1, 0, 0);
        number.SetValue( 120.44, 1, 0, 1);
        number.SetValue(  38.62, 1, 0, 2);
        number.SetValue( 526.82, 1, 0, 3);
        number.SetValue(1704.62, 1, 0, 4);
        number.SetValue(  56.85, 1, 1, 0);
        number.SetValue( 105.48, 1, 1, 1);
        number.SetValue( 363.31, 1, 1, 2);
        number.SetValue( 172.62, 1, 1, 3);
        number.SetValue( 128.48, 1, 1, 4);
        number.SetValue( 906.68, 1, 2, 0);
        number.SetValue(  47.12, 1, 2, 1);
        number.SetValue(-166.07, 1, 2, 2);
        number.SetValue(4444.26, 1, 2, 3);
        number.SetValue( 408.62, 1, 2, 4);

        WriteLine("Number: {0}", number.GetValue(0, 2, 4));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Number: 386.73
=================================
Press any key to continue . . .

To access each member of the array, you can use three for loops. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var number = Array.CreateInstance(typeof(double), 2, 3, 5);

        number.SetValue(  12.44, 0, 0, 0);
        number.SetValue( 525.38, 0, 0, 1);
        number.SetValue(  -6.28, 0, 0, 2);
        number.SetValue(2448.32, 0, 0, 3);
        number.SetValue( 632.04, 0, 0, 4);
        number.SetValue(-378.05, 0, 1, 0);
        number.SetValue(  48.14, 0, 1, 1);
        number.SetValue( 634.18, 0, 1, 2);
        number.SetValue( 762.48, 0, 1, 3);
        number.SetValue(  83.02, 0, 1, 4);
        number.SetValue(  64.92, 0, 2, 0);
        number.SetValue(  -7.44, 0, 2, 1);
        number.SetValue(  86.74, 0, 2, 2);
        number.SetValue(-534.60, 0, 2, 3);
        number.SetValue( 386.73, 0, 2, 4);
        number.SetValue(  48.02, 1, 0, 0);
        number.SetValue( 120.44, 1, 0, 1);
        number.SetValue(  38.62, 1, 0, 2);
        number.SetValue( 526.82, 1, 0, 3);
        number.SetValue(1704.62, 1, 0, 4);
        number.SetValue(  56.85, 1, 1, 0);
        number.SetValue( 105.48, 1, 1, 1);
        number.SetValue( 363.31, 1, 1, 2);
        number.SetValue( 172.62, 1, 1, 3);
        number.SetValue( 128.48, 1, 1, 4);
        number.SetValue( 906.68, 1, 2, 0);
        number.SetValue(  47.12, 1, 2, 1);
        number.SetValue(-166.07, 1, 2, 2);
        number.SetValue(4444.26, 1, 2, 3);
        number.SetValue( 408.62, 1, 2, 4);

        for (int m = 0; m < number.GetLength(0); m++)
            for (int n = 0; n < number.GetLength(1); n++)
                for (int element = 0; element < number.GetLength(2); element++)
                    WriteLine("Number: {0}", number.GetValue(m, n, element));

        WriteLine("=================================");
        return 0;
    }
}

This would produce:

Number: 12.44
Number: 525.38
Number: -6.28
Number: 2448.32
Number: 632.04
Number: -378.05
Number: 48.14
Number: 634.18
Number: 762.48
Number: 83.02
Number: 64.92
Number: -7.44
Number: 86.74
Number: -534.6
Number: 386.73
Number: 48.02
Number: 120.44
Number: 38.62
Number: 526.82
Number: 1704.62
Number: 56.85
Number: 105.48
Number: 363.31
Number: 172.62
Number: 128.48
Number: 906.68
Number: 47.12
Number: -166.07
Number: 4444.26
Number: 408.62
=================================
Press any key to continue . . .

You can also use a foreach loop to access each member of the array. Here is an example:

using System;
using static System.Console;

public class Exercise
{
    public static int Main(string[] args)
    {
        var number = Array.CreateInstance(typeof(double), 2, 3, 5);

        number.SetValue(  12.44, 0, 0, 0);
        number.SetValue( 525.38, 0, 0, 1);
        number.SetValue(  -6.28, 0, 0, 2);
        number.SetValue(2448.32, 0, 0, 3);
        number.SetValue( 632.04, 0, 0, 4);
        number.SetValue(-378.05, 0, 1, 0);
        number.SetValue(  48.14, 0, 1, 1);
        number.SetValue( 634.18, 0, 1, 2);
        number.SetValue( 762.48, 0, 1, 3);
        number.SetValue(  83.02, 0, 1, 4);
        number.SetValue(  64.92, 0, 2, 0);
        number.SetValue(  -7.44, 0, 2, 1);
        number.SetValue(  86.74, 0, 2, 2);
        number.SetValue(-534.60, 0, 2, 3);
        number.SetValue( 386.73, 0, 2, 4);
        number.SetValue(  48.02, 1, 0, 0);
        number.SetValue( 120.44, 1, 0, 1);
        number.SetValue(  38.62, 1, 0, 2);
        number.SetValue( 526.82, 1, 0, 3);
        number.SetValue(1704.62, 1, 0, 4);
        number.SetValue(  56.85, 1, 1, 0);
        number.SetValue( 105.48, 1, 1, 1);
        number.SetValue( 363.31, 1, 1, 2);
        number.SetValue( 172.62, 1, 1, 3);
        number.SetValue( 128.48, 1, 1, 4);
        number.SetValue( 906.68, 1, 2, 0);
        number.SetValue(  47.12, 1, 2, 1);
        number.SetValue(-166.07, 1, 2, 2);
        number.SetValue(4444.26, 1, 2, 3);
        number.SetValue( 408.62, 1, 2, 4);

        foreach (double nbr in number)
            WriteLine("Number: {0}", nbr);

        WriteLine("=================================");
        return 0;
    }
}

Multidimensional Arrays

The Array class supports all dimensions of arrays beyond three. To create a multidimensional array, the class is equipped with the following version of its CreateInstance() method:

public static Array CreateInstance(Type elementType, params int[] lengths)

To add elements to the list, you can use the following equivalent version of the SetValue() method:

public void SetValue(object value, params int[] indices)

To get the value of an element, you would call the following version of the GetValue() method:

public Object GetValue(params int[] indices)

Getting Other Information About an Array

The Lower Bound of an Array

To better manage an array, the compiler must always be able to locate its highest and its lowest members. This is particularly important because an array must have a size.

The lowest member of an array can be located using the Array.GetLowerBound() method. Its syntax is:

public int GetLowerBound(int dimension);

The Upper Bound of an Array

The highest member of an array can be located using the Array.GetUpperBound() method. Its syntax is:

public int GetUpperBound(int dimension);

In both cases, the dimension argument is the rank of the array. For a single-dimensional array, as those we have always used so far, this parameter must have the value of 0.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2008-2017, FunctionX Next