Arrays
C# supports single-dimensional as well as multidimensional arrays. Here is what array declaration looks like:
int[] array1 = new int[4];
This is how you normally access its elements using subscript operator:
array1[0] = 0;
array1[1] = 1;
array1[2] = 2;
array1[3] = 3;
Now I'mma show you exactly the same array, but with initialization upon declaration:
int[] array1 = new int[4] {0,1,2,3};
Convenient, isn't it? Ok, before we go any further, I wanna show you a couple of ways to iterate through an array:
for (int i = 0; i < array1.Length; ++i)
Console.WriteLine(array1[i]);
foreach (int element in array1)
Console.WriteLine(element);
I think it's time to get familiar with multidimensional arrays.
int[,] array2 = new int[4,4];
int[,] array2 = new int[4,4];
{
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 },
{ 0, 1, 2, 3 }
};
Array.Length property returns total length of the array including all dimensions. If you wanna know how many elements are in concrete dimension, use Array.GetLength(dimension). If you wanna know how many dimensions are in your array, use Array.Rank property.
foreach doesnt care about dimensionality of your array, it will iterate from the beginning to the end, dimension by dimension:
foreach (int element in array2)
Console.WriteLine(element);
If you wanna use regular for loop with indices, it's a little bit more tricky:
for (int i = 0; i < array2.GetLength(0); ++i)
for (int k = 0; k < array2.GetLength(1); ++k)
Console.WriteLine(array2[i,k]);
Collections
C# also got plenty of different collections, let's take a brief look at some of them, starting with dictionary. Ok this is what dictionary looks like:
Dictionary<string, int> dictionary =
new Dictionary<string, int>();
Basically it's just an associative array storing key-value pairs. The first generic type parameter is a type of key, the second one is a type of value respectively. Let me show you how this thing works.
You add key-value pairs this way:
dictionary.Add("One", 1);
dictionary.Add("Two", 2);
And that's how you access its values:
int one = dictionary["One"];
int two = dictionary["Two"];
Ok, now I wanna show you some lists. Let's start with regular List which looks like this:
List<string> list = new List<string>();
And works like this:
list.Add("One");
list.Add("Two");
list.Add("Three");
string One = list[0];
string Two = list[1];
string Three = list[2];
As you can see List behaves just like array, but its more advanced and flexible. Ok, the last one is gonna be LinkedList. This is what it looks like:
LinkedList<string> linkedList =
new LinkedList<string>();
You can add nodes at any end:
linkedList.AddFirst("first");
linkedList.AddLast("last");
And access them in the following manner:
string first = linkedList.First.Value;
string last = linkedList.First.Next.Value;
foreach (var element in linkedList){}