Sobes.tech
Junior

Que objetos podem ser utilizados num ciclo foreach?

sobes.tech IA

Resposta da IA

No ciclo foreach podem ser utilizados objetos que implementem a interface System.Collections.IEnumerable ou System.Collections.Generic.IEnumerable<T>.

Principais tipos de objetos:

  • Arrays (unidimensionais e multidimensionais)
  • Coleções que implementam IEnumerable ou IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> e Stack<T>
    • Outras classes dos espaços de nomes System.Collections e System.Collections.Generic
  • Strings (System.String - iteram por caracteres)
  • Objetos retornados por consultas LINQ
  • Tipos de dados próprios que implementem uma das interfaces mencionadas.

Exemplo:

// Array
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)
{
    // ...
}

// string
string text = "hello";
foreach (char c in text)
{
    // ...
}

// Dictionary<TKey, TValue> itera sobre 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
}

// Classe própria que implementa 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; // Uso do iterador
        }
    }

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

// Uso da classe própria
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}