Sobes.tech
Junior

Какви обекти могат да бъдат използвани в цикъла foreach?

sobes.tech AI

Отговор от AI

В цикъла foreach могат да бъдат използвани обекти, които реализират интерфейса System.Collections.IEnumerable или System.Collections.Generic.IEnumerable<T>.

Основни типове обекти:

  • Масиви (едномерни и многомерни)
  • Колекции, които реализират IEnumerable или IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> и Stack<T>
    • Други класове от пространствата имена System.Collections и System.Collections.Generic
  • Стриймове (System.String - итерация по символи)
  • Обекти, връщани от LINQ заявки
  • Собствени типове данни, които реализират някой от посочените интерфейси.

Пример:

// Масив
string[] colors = {"червен", "зелен", "син"};
foreach (string color in colors)
{
    // ...
}

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

// стринг
string text = "здравей";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> итерация по 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
}

// Собствен клас, реализиращ 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; // Използване на итератора
        }
    }

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

// Използване на собствен клас
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}