Array
Un array memorizza un numero fisso di valori dello stesso tipo, ciascuno raggiungibile con un indice che parte da 0.
Come funziona
Creare, leggere, modificare, scorrere e ordinare array C#, anche bidimensionali.
Length dà la dimensione e ^1 legge l'ultimo elemento. foreach visita ogni elemento, Array.Sort ordina sul posto, new int[3] parte con zeri e int[,] crea una griglia indicizzata per riga e colonna.
Guarda come funziona
Fai clic su una casella o sposta il cursore per scegliere un indice. Inserisci o elimina per vedere perché tutti gli elementi successivi devono spostarsi.
Esempio C# eseguibile
using System;
using System.Linq;
class Program
{
static void Main()
{
// An array has a fixed length set when it is created.
int[] scores = { 72, 95, 88, 64 };
Console.WriteLine($"Length: {scores.Length}");
Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");
scores[3] = 70; // elements can be changed, the length cannot
int sum = 0;
foreach (int score in scores)
{
sum += score;
}
Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");
// Array.Sort sorts in place; string.Join prints the elements.
Array.Sort(scores);
Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
Console.WriteLine($"Max: {scores.Max()}");
// new int[3] creates an array of zeros.
int[] counts = new int[3];
counts[1] = 5;
Console.WriteLine($"Counts: {string.Join(" ", counts)}");
// A 2D array is indexed by row and column.
int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
}
}
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6Esercitati con il debugger
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Count Positive Numbers Count the values greater than zero in a list. Facile
- Running Sum Replace each value with the total so far. Facile
- Swap First and Last Exchange the first and last items of a list. Facile