Sobes.tech
Junior

Jaké objekty lze použít v cyklu foreach?

sobes.tech AI

Odpověď od AI

V cyklu foreach lze použít objekty, které implementují rozhraní System.Collections.IEnumerable nebo System.Collections.Generic.IEnumerable<T>.

Hlavní typy objektů:

  • Pole (jednorozměrná a vícerozměrná)
  • Kolekce, které implementují IEnumerable nebo IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> a Stack<T>
    • Další třídy v názvových prostorech System.Collections a System.Collections.Generic
  • Řetězce (System.String - iterují přes znaky)
  • Objekty vrácené LINQ dotazy
  • Vlastní datové typy, které implementují některé z výše uvedených rozhraní.

Pří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)
{
    // ...
}

// řetězec
string text = "ahoj";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> iteruje přes 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í třída implementující 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žití iterátoru
        }
    }

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

// Použití vlastní třídy
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}