Sobes.tech
Junior

¿Qué objetos pueden ser utilizados en un ciclo foreach?

sobes.tech AI

Respuesta de la IA

En el ciclo foreach pueden ser utilizados objetos que implementen la interfaz System.Collections.IEnumerable o System.Collections.Generic.IEnumerable<T>.

Tipos principales de objetos:

  • Arrays (unidimensionales y multidimensionales)
  • Colecciones que implementan IEnumerable o IEnumerable<T>:
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> y Stack<T>
    • Otras clases de los espacios de nombres System.Collections y System.Collections.Generic
  • Cadenas (System.String - iteran por caracteres)
  • Objetos devueltos por consultas LINQ
  • Tipos de datos propios que implementen alguna de las interfaces mencionadas.

Ejemplo:

// 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> iterates over 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
}

// Custom class implementing 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; // Using iterator
        }
    }

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

// Using custom class
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}