Kolekcje: lista List<T>

Kolekcje i LINQ - Podstawy C# (csharp)

List<T> to tablica, która sama rośnie: w nawiasach ostrych podajemy typ elementów (List<int>, List<string>). Add dopisuje na końcu, Insert wstawia pod indeks, Remove usuwa pierwszy element o danej wartości, a RemoveAt element pod indeksem. Liczbę elementów podaje właściwość Count (w tablicy: Length), Contains sprawdza, czy element jest na liście, a IndexOf zwraca jego indeks (albo -1). string.Join(", ", lista) skleja elementy w jeden napis z separatorem.
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
  static void Main(string[] args)
  {
    List<string> names = new List<string>();
    names.Add("Ola");
    names.Add("Kuba");
    names.Add("Ewa");
    Console.WriteLine($"Lista: {string.Join(", ", names)} (Count = {names.Count})");

    names.Insert(1, "Adam");
    Console.WriteLine($"Po Insert(1, Adam): {string.Join(", ", names)}");

    names.Remove("Kuba");
    names.RemoveAt(0);
    Console.WriteLine($"Po usunięciu: {string.Join(", ", names)}");

    Console.WriteLine($"Pierwszy element: {names[0]}");
    Console.WriteLine($"Czy jest Ewa? {names.Contains("Ewa")}");
    Console.WriteLine($"Indeks Ewy: {names.IndexOf("Ewa")}, indeks Oli: {names.IndexOf("Ola")}");

    List<int> numbers = new List<int> { 5, 3, 9 };
    numbers.AddRange(new[] { 1, 7 });
    numbers.Sort();
    Console.WriteLine($"Posortowane liczby: {string.Join(" ", numbers)}");
  }
}

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

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