How to loop through a collection that supports IEnumerable?
Using foreach Statement The standard option to iterate over the List in C# is using a foreach loop. Then, we can perform any action on each element of the List. The following code example demonstrates its usage by displaying the contents of the list to the console.
As mentioned in the existing answers, an IEnumerable collection cannot be modified by trying to assign a new value to one of its elements.
IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
A regular for each will do:
foreach (var item in collection) { // do your stuff }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With