Sobes.tech
Junior

Jakie obiekty mogą być używane w pętli foreach?

sobes.tech AI

Odpowiedź od AI

W pętli foreach można używać obiektów implementujących interfejs System.Collections.IEnumerable lub System.Collections.Generic.IEnumerable<T>.

Główne typy obiektów:

  • Tablice (jednowymiarowe i wielowymiarowe)
  • Kolekcje implementujące IEnumerable lub IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> i Stack<T>
    • Inne klasy z przestrzeni nazw System.Collections i System.Collections.Generic
  • Ciągi znaków (System.String - iterują po znakach)
  • Obiekty zwracane przez zapytania LINQ
  • Własne typy danych implementujące jedną z wymienionych interfejsów.

Przykład:

// Tablica
string[] colors = {"red", "green", "blue"};
foreach (string color in colors)
{
    // ...
}

// List<T>
List<int> numbers = new List<int> {1, 2, 3, 4, 5};
foreach (int number in numbers)
{
    // ...
}

// ciąg znaków
string text = "hello";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> iteruje po KeyValuePair<TKey, TValue>
Dictionary<string, int> ages = new Dictionary<string, int>
{
    {"Alice", 30},
    {"Bob", 25}
};
foreach (KeyValuePair<string, int> entry in ages)
{
    // entry.Key, entry.Value
}

// Własna klasa implementująca IEnumerable<T>
public class MyCollection : IEnumerable<int>
{
    private int[] _data = {10, 20, 30};

    public IEnumerator<int> GetEnumerator()
    {
        foreach (var item in _data)
        {
            yield return item; // Użycie iteratora
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

// Użycie własnej klasy
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}