Sobes.tech
Junior

Quels objets peuvent être utilisés dans une boucle foreach ?

sobes.tech IA

Réponse de l'IA

Dans la boucle foreach, il est possible d'utiliser des objets qui implémentent l'interface System.Collections.IEnumerable ou System.Collections.Generic.IEnumerable<T>.

Types principaux d'objets :

  • Tableaux (monodimensionnels et multidimensionnels)
  • Collections qui implémentent IEnumerable ou IEnumerable<T> :
    • List<T>
    • Dictionary<TKey, TValue>
    • HashSet<T>
    • Queue<T> et Stack<T>
    • Autres classes des espaces de noms System.Collections et System.Collections.Generic
  • Chaînes (System.String - itèrent par caractères)
  • Objets retournés par des requêtes LINQ
  • Types de données propres qui implémentent l'une des interfaces mentionnées.

Exemple :

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

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

// Dictionary<TKey, TValue> itère sur 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 personnalisée implémentant 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; // Utilisation de l'itérateur
        }
    }

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

// Utilisation de la classe personnalisée
MyCollection myCollection = new MyCollection();
foreach (int item in myCollection)
{
    // ...
}