Lesson 5: Arrays and collections

Woot! We are almost half way there! Anyways, we have come to one of the more difficult sections of programming. Arrays requires you to use everything you have learned so far. If you need to, take some time to review the last few lessons.

Here is a vocab refresher:

  1. Declare means to name and make a variable, object, etc. This usually reserves a space in the memory, so don’t pull a ubisoft and waste all the space!
  2. Initialization means to fill the variable or object that you have declared with data.

Arrays

What is an Array? An array is a series of objects or variables that are the same type.
Arrays in C# work similarly to how arrays work in everything else, including Java. However, there are some minor differences. First thing you should know is that arrays in C# are written differently.

When declaring an array, the square brackets ([]) must come after the type, not the identifier(name). Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];

Secondly, the size of the array is not part of its type as it is in other C like languages. This allows you to declare an array and assign any array of int objects to it, regardless of the array’s length. If you don’t get this, it doesn’t really matter, as it just means that arrays are slightly more flexible.

Now that we got the differences over with for all those keeners out there, we move on to a refresher on what arrays look like. Arrays are declared in the following format:

datatype[] identifier;

Here is what it means:

  • datatype states the type of data being stored, like an int or a string
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • identifier is the name of the array

Things in an array are called elements, and each element has a number, similar to an address. These are called indexes. Indexes always start with 0, because in programming, numbers start counting from 0. For example if you have the following code, Yasuo will be index 0 and Katarina will be index 1.

string[] rito = {"Yasuo","Katarina"};
//and therefore
//rito[0] == "Yasuo"
//rito[1] == "Katarina"

But before we dive into the different parts of arrays, and how to use them, lets look at types of arrays.

As with Java, there are 3 types of arrays.

  1. Single-Dimension Array
  2. Multidimensional Array
  3. Jagged Array

Single-Dimension Array are your normal arrays. Since arrays are series of things, and single-dimension array is just 1 series of things in a single line. EZ.

Multidimensional array are arrays arrays the are not just in a straight line, but in multiple dimensions. The most common is the rectangular or the 2D array. The first index is the one dimension, while the next one is the second. Think of them as a table, where the first index is the row number and the second index is the column. Take a look at this table:

ColumnĀ 0 Column 1 Column 2
Row 0 a[0,0] a[0,1] a[0,2]
Row 1 a[1,0] a[1,1] a[1, 2]
Row 2 a[2,0] a[2,1] a[2,2]

 

Finally, Jagged arrays are arrays of arrays. Yes, they are just arrays in one of the indexes of an array. Arrayception!

So how do we declare arrays? Here is the format:

datatype[] identifier;

And here is an example:

//normal arrays
string[] listOfNames;

//multidimensional arrays
string[,] names;

//jagged arrays
string[][] names;

Thats is it! Declaring arrays in C# does not assign it in the memory. That mean declaring arrays does not mean you actually made an array! They must be initialized. When you have finished declaring an array, you can initialize it with stuff.
To initialize arrays you do the following:

//normal 1D arrays
int[] numbers = new int[5]; /* or */
int[] numbers = new int[];

//multidimensional arrays
string[,] names = new string[5,4];

//jagged arrays
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++) 
{
   scores[x] = new byte[4];
}

There are multiple ways of putting or retrieving information in an array. Here is the few ways you can do this:

//You can do it by index number
int[] sample = new int[];
sample[0] = 9;
sample[1] = 45;

//at the time of declaration like this
int[] sample = {9, 45};

//or like this
int[] sample = new int[]  {9, 45};

//or from another array
int[] temp = {9, 45}
int[] sample = temp;

//You can also specify the size of your array when creating an array
int[] sample = new int[2]  {9, 45};

and it is very similar for the different types of array:

//multidimensional
int [,] a = int [3,4] = {  
 {0, 1, 2, 3} ,  
 {4, 5, 6, 7} ,  
 {8, 9, 10, 11} 
};

//jagged
int[][] sample = new int[2][]{new int[]{1,2,5},new int[]{85,69,87,88}};

Now that we have arrays that can store information, we need to know how to retrieve it. It is identical to how you would be putting information in an array, but in the opposite direction. Refer to the section above. In most cases it is the array identifier followed by the index. Usually you would store this in a variable like the following:

int[] sample = new int[]  {9, 45};
int printThisNumber = sample[1];
Console.WriteLine(printThisNumber);

//the console will output 45. We retrieved it by setting a variable to sample[1]. 

To retrieve a whole section of code we can use a for loop, that loops through the array. Or we can use a foreach loop, as thought by the previous lesson. Here is an example just in case:

//foreach
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
   System.Console.WriteLine(i);
}

//this works on multidimensional arrays too!
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
   Console.Write("{0} ", i);
}

// output of the multidimensional array:
// 9 99 3 33 5 55
// however you may want to use multiple nested for loops instead for more 
// control instead of just retrieving all the info in the 
// multidimensional array


//and normal for loops:
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
for (int i = 0; i < numbers.Length; i++)
	{
	    int consolePrintVariable = numbers [i];
	    Console.WriteLine(consolePrintVariable);
	}

So here are some few more facts about arrays in C#. Arrays in C# cannot not be resized after they are initialized. That mean you cannot add, insert or remove indexes. However you can copy and array, change it, and put it back into a different array. Second, arrays are objects, so they have build in variables and functions. One of the property is the .Length, and it returns how long the array is. Also, it is recommended to use a foreach loop instead of a for loop, since it is simpler, and less mistakes will be made.

Links to tutorials and further reading:
http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
http://www.tutorialspoint.com/csharp/csharp_arrays.htm

Next up is collections. This is the new, radical way of storing information and is an alternative to arrays. Collections are specialized classes (objects) for data retrieval and storage. In C# there are two main collection classes and a few other minor collections. The first is the ArrayList and the second is List. The minor ones that we will not be going into detail are Hashtable, SortedList, Stack, Queue, and BitArray.

List and ArrayList

ArrayList represents collections of objects that can be indexed individually. They are the collections alternative to Arrays, and have array like features. That means every single thing in the ArrayList collection has an index, similar to arrays. However, ArrayList are like Arrays on steroids, as you can add, remove, and insert into an ArrayList and it will automatically resize the collection. It also has automatic memory allocation, and cool features like sorting, searching, advanced index information, and much more. ArrayLists also have some useful methods/functions built in.

However, ArrayLists are still considered old school, and it is recommended to use List instead. The reason is that ArrayList is its own class type, is specific, and sometimes can’t be mixed with certain types (string, int, double, etc). Also, ArrayList is an array like class, and might have difficulty with certain types. However, List is generic, and is considered type safe, meaning you can use it with any types! The only time you will need to use ArrayList is when there are ArrayList specific functions that are not in the generic List.

To declare and initialize a List do the following:
Remember to using the System.Collections.Generic! It should be automatically be imported by default

using System.Collections.Generic;
List<type> list = new List<type>();

//so a list for int will be:
List<int> list = new List<int>();

//and to add to a list you will use the add method like this:
list.Add(2);

Here is a full example of a Add, and a list print using the foreach loop.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arrays
{
class Program
{
static void Main(string[] args)
{
List listName = new List();
listName.Add(2);
listName.Add(125362);
listName.Add(225);

foreach (int getNumber in listName) // Loop through List with foreach
{
Console.WriteLine(getNumber);
}
Console.ReadKey();
}

}
}

You can retrieve indexes by using the same method as an normal array. Eg. listName[2];
If you want to see all the List functions and properties, make a List (like listName) above, press “.” and take a look at the intellisense box to see what functions there are. Here are some common functions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> listName = new List<string>();
            listName.Add("Rito");
            listName.Add("OP");
            listName.Add("kalista");
            listName.Add("thresh");
            //just normal
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }

            //spacer in console, pls ingnore
            Console.WriteLine("");

            //a sort (Usullay alphabetical, etc.
            listName.Sort();
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }
            //spacer in console, pls ingnore
            Console.WriteLine("");

            // a count of how many
            int howMany = listName.Count();
            Console.WriteLine("There is {0} elements", howMany);

            //finding stuff in an List using a Contains
            bool opExists = listName.Contains("OP");
            if (opExists) 
            {
                Console.WriteLine("Kalista is OP because people suck at countering");
            }
            else
            {
                Console.WriteLine("Kalista is not OP!");
            }

            //you can also find the index number of something using IndexOf
            int indexofOP = listName.IndexOf("OP");
            Console.WriteLine("Index of OP is at {0}", indexofOP);

            //spacer in console, pls ingnore
            Console.WriteLine("");

            //you can insert into an List
            listName.Insert(2, "New Inserted");
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }

            Console.ReadKey();
            //there is much more!
        }
    }
}

There are many more. I want you to now go online and find one that I didn’t mention in the example above that is useful. Here are some sites that you can check out:
http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
http://www.dotnetperls.com/list
http://csharp.net-informations.com/collection/list.htm

Other Collections:

Class Description and Useage
Hashtable It uses a key to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.

SortedList It uses a key as well as an index to access the items in a list.

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value.

Stack It represents a last-in, first out collection of object.

It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is calledpopping the item.

Queue It represents a first-in, first out collection of object.It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is calleddeque.
BitArray It represents an array of the binary representation using the values 1 and 0.

It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.

Leave a Reply

Your email address will not be published. Required fields are marked *