TOC

This article is currently in the process of being translated into Vietnamese (~26% done).

Collections:

Arrays

Mảng (array) là một tập hợp các phần tử, ví dụ chuỗi. Bạn có thể dùng chúng để lưu các phần tử vào một nhóm, và thực hiện nhiều thao tác trên đó, ví dụ sắp xếp. Bên cạnh đó, nhiều phương thức trong framework cho phép thao tác mảng để có thể thao tác một loạt các phần tử thay vì chỉ một. Vậy rất quan trọng để hiểu về mảng.

Khai báo mảng giống biến, với một cặp dấu [] theo sau kiểu dữ liệu như sau:

string[] names;

Bạn cần khởi tạo mảng để dùng như sau:

string[] names = new string[2];

Con số (2) là kích thước của mảng, đó là số phần tử của mảng. Để gán giá trị cho mảng thì ta có thể làm đơn giản như sau:

names[0] = "John Doe";

But why 0? As it is with so many things in the world of programming, the counting starts from 0 instead of 1. So the first item is indexed as 0, the next as 1 and so on. You should remember this when filling the array with items, because overfilling it will cause an exception. When you look at the initializer, setting the array to a size of 2, it might seem natural to put item number 0, 1 and 2 into it, but this is one item too much. If you do it, an exception will be thrown. We will discuss exceptions in a later chapter.

Earlier, we learned about loops, and obviously these go great with arrays. The most common way of getting data out of an array, is to loop through it and perform some sort of operation with each value. Let's use the array from before, to make a real example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    string[] names = new string[2];

    names[0] = "John Doe";
    names[1] = "Jane Doe";

    foreach(string s in names)
Console.WriteLine(s);

    Console.ReadLine();
}
    }
}

We use the foreach loop, because it's the easiest, but of course we could have used one of the other types of loop instead. The for loop is good with arrays as well, for instance if you need to count each item, like this:

for(int i = 0; i < names.Length; i++)
    Console.WriteLine("Item number " + i + ": " + names[i]);

It's actually very simple. We use the Length property of the array to decide how many times the loop should iterate, and then we use the counter (i) to output where we are in the process, as well as get the item from the array. Just like we used a number, a so called indexer, to put items into the array, we can use it to get a specific item out again.

I told you earlier that we could use an array to sort a range of values, and it's actually very easy. The Array class contains a bunch of smart methods for working with arrays. This example will use numbers instead of strings, just to try something else, but it could just as easily have been strings. I wish to show you another way of populating an array, which is much easier if you have a small, predefined set of items that you wish to put into your array. Take a look:

int[] numbers = new int[5] { 4, 3, 8, 0, 5 };

With one line, we have created an array with a size of 5, and filled it with 5 integers. By filling the array like this, you get an extra advantage, since the compiler will check and make sure that you don't put too many items into the array. Try adding a number more - you will see the compiler complain about it.

Actually, it can be done even shorter, like this:

int[] numbers = { 4, 3, 8, 0, 5 };

This is short, and you don't have to specify a size. The first approach may be easier to read later on though.

Let's try sorting the array - here's a complete example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
static void Main(string[] args)
{
    int[] numbers = { 4, 3, 8, 0, 5 };

    Array.Sort(numbers);

    foreach(int i in numbers)
Console.WriteLine(i);

    Console.ReadLine();
}
    }
}

Lệnh mới ở đây là Array.Sort. Nó có thể có nhiều tham số, nhiều loại sắp xếp nhưng trong trường hợp của chúng ta chỉ lấy mảng là đầu vào. Bạn có thể thấy ở kết quả chúng ta có mảng đã được sắp xếp. Lớp Array cũng có các phương thức khác như phương thức Reverse(). Bạn có thể tìm trong documentation để xem toàn bộ đặc điểm của lớp Array.

The arrays we have used so far have only had one dimension. However, C# arrays can be multidimensional, sometimes referred to as arrays in arrays. Multidimensional arrays come in two flavors with C#: Rectangular arrays and jagged arrays. The difference is that with rectangular arrays, all the dimensions have to be the same size, hence the name rectangular. A jagged array can have dimensions of various sizes. Multidimensional arrays are a heavy subject, and a bit out of the scope of this tutorial.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!