TOC

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

Sbírky:

Pole

Arrays works as collections of items, for instance strings. You can use them to gather items in a single group, and perform various operations on them, e.g. sorting. Besides that, several methods within the framework work on arrays, to make it possible to accept a range of items instead of just one. This fact alone makes it important to know a bit about arrays.

Pole jsou deklarovány podobně jako proměnné, s použitím hranatých závorek [] za datovým typem, takto:

string[] names;

Musíte vytvořit instanci pole pro jeho použití, což se dělá takto:

string[] names = new string[2];

Číslo (2) je velikost pole, tedy množství položek, které můžeme umístit do pole. Vložení položek do pole je také celkem jednoduché:

names[0] = "John Doe";

Ale proč 0? Stejně jako je tomu s mnoha dalšími věcmi ve světě programování, počítání začíná od nuly místo od jedné. Takže první položka má index 0, další položka 1 a tak dále. Je nutné na to myslet, ve chvíli kdy plníš pole položkami, protože přeplnění pole způsobí chybu. Když se podíváš na inicializaci, nastavení velikosti pole na 2, může se zdát přirozené naplnit pole čísly 0, 1 a 2, ale to je o jedno číslo víc. Pokud to uděláš, objeví se chybová hláška. Chybové hlášky budou probírány v dalších kapitolách.

Dřívě jsme se učili o cyklech a očividně jdou skvěle dohromady s poli. Nejběžnější cesta jak dostat data z pole je prohledat je pomocí cyklu a provézt nějaký typ operace s každou hodnotou. Pojďme použít předešlé pole pro názorný příklad:

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();
}
    }
}

Používáme cyklus foreach, protože je to nejjednodušší cyklus, ale samozřejmě bychom místo toho mohli použít jeden z ostatních typů cyklů. Cyklus je také dobrý s polem (array) , například pokud potřebujete počítat každou položku, jako je zde:

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

Vlastně je to velice jednoduché. Použijeme vlastnost Length (délka) ke zjištění počtu kolikrát se smyčka opakuje a čítač (i) kam se hodnota průběžně ukládá a můžeme ji použít pro zjištění, kde v poli jsme. Stejně jako používáme čísla jako indexy pro vložení do pole, můžeme je využít pro vyhledání určité položky z pole.

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.

Vlastně je možný kratší zápis, jako tento:

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

Toto je krátké a nemusíte určovat velikost pole. První přístup může být později jednodušší.

Pokusme se roztřídit pole - zde je úplný příklad:

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();
}
    }
}

The only real new thing here is the Array.Sort command. It can take various parameters, for various kinds of sorting, but in this case, it simply takes our array. As you can see from the result, our array has been sorted. The Array class has other methods as well, for instance the Reverse() method. You can look it up in the documentation to see all the features of the Array class.

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!