Sobes.tech
Junior — Middle

What types of collections or data structures are suitable for iteration using the foreach operator?

sobes.tech AI

Answer from AI

In C#, the foreach operator can be used to iterate over any collections or data structures that implement the IEnumerable or IEnumerable<T> interface.

Suitable collections:

  • Arrays (int[], string[], etc.)
  • Lists (List<T>)
  • Sets (HashSet<T>)
  • Dictionaries (Dictionary<TKey, TValue>) — iterates over key-value pairs
  • Queues (Queue<T>), stacks (Stack<T>)
  • Any custom collections implementing IEnumerable

Example:

List<string> names = new List<string> { "Anna", "Bob", "Charlie" };

foreach (var name in names)
{
    Console.WriteLine(name);
}

Thus, foreach works with any iterable objects, making it versatile for traversing collections.

What types of collections or data structures are… - sobes.tech