Sobes.tech
Junior

Aké objekty môžu byť použité v cykle foreach?

sobes.tech AI

Odpoveď od AI

V slučke foreach je možné použiť objekty, ktoré implementujú rozhranie System.Collections.IEnumerable alebo System.Collections.Generic.IEnumerable<T>.

Hlavné typy objektov:

  • Polia (jednodimenzionálne a viacrozmerné)
  • Kolekcie, ktoré implementujú IEnumerable alebo IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> a Stack<T>
    • Iné triedy z priestorov mien System.Collections a System.Collections.Generic
  • Reťazce (System.String - iterujú cez znaky)
  • Objekty, ktoré vracajú LINQ dotazy
  • Vlastné dátové typy, ktoré implementujú niektoré z uvedených rozhraní.

Príklad:

// Pole
string[] colors = {"červená", "zelená", "modrá"};
foreach (string color in colors)
{
    // ...
}

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

// reťazec
string text = "ahoj";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> iteruje cez 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
}

// Vlastná trieda, ktorá implementuje 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; // Použitie iterátora
        }
    }

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

// Použitie vlastnej triedy
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}