Pętla foreach po tablicach i liście

Wyjątki i pętla foreach - Podstawy C# (csharp)

Pętla foreach (typ element in kolekcja) przechodzi po kolejnych elementach tablicy lub listy bez używania indeksu - jest krótsza i nie da się w niej pomylić zakresu. Dla tablicy dwuwymiarowej int[,] foreach przechodzi po wszystkich komórkach wiersz po wierszu, a dla tablicy postrzępionej int[][] kolejne elementy to całe wiersze. Zmiennej pętli nie można przypisać nowej wartości (błąd kompilacji), a gdy potrzebny jest indeks, używamy zwykłej pętli for.
using System;
using System.Collections.Generic;

class Program
{
  static void Main(string[] args)
  {
    int[] numbers = { 1, 2, 3, 4, 5 };
    Console.Write("Pętla for:     ");
    for (int i = 0; i < numbers.Length; i++)
    {
      Console.Write(numbers[i] + " ");
    }
    Console.WriteLine();
    Console.Write("Pętla foreach: ");
    foreach (int number in numbers)
    {
      Console.Write(number + " ");
    }
    Console.WriteLine();

    List<string> fruits = new List<string> { "jabłko", "gruszka", "banan" };
    foreach (string fruit in fruits)
    {
      Console.WriteLine($"- {fruit}");
    }

    int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
    int total = 0;
    foreach (int cell in grid)
    {
      total += cell;
    }
    Console.WriteLine($"Suma komórek int[,]: {total}");

    int[][] jagged = { new[] { 1, 2 }, new[] { 3, 4, 5 }, new[] { 6 } };
    foreach (int[] row in jagged)
    {
      foreach (int value in row)
      {
        Console.Write(value + " ");
      }
      Console.WriteLine($"(długość {row.Length})");
    }
  }
}

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu Podstawy C#·Zaloguj się, aby zapisać postęp na koncie.