How to iterate over a collection that supports IEnumerable?

How to loop through a collection that supports IEnumerable?

+43
c # foreach for-loop ienumerable
Oct 07 '09 at 16:47
source share
4 answers

Regularly for everyone there will be:

foreach (var item in collection) { // do your stuff } 
+75
Oct 07 '09 at 16:48
source share

Along with the methods already proposed for using the foreach , I thought that I also mention that any object that implements IEnumerable also provides an IEnumerator interface using the GetEnumerator method. Although this method is generally not needed, it can be used to manually iterate over collections and is especially useful when writing custom extension methods for collections.

 IEnumerable<T> mySequence; using (var sequenceEnum = mySequence.GetEnumerator()) { while (sequenceEnum.MoveNext()) { // Do something with sequenceEnum.Current. } } 

A prime example is that you want to iterate over two sequences simultaneously, which is not possible in a foreach .

+65
Oct 07 '09 at 16:54
source share

or even a very classic old fashion method

 for(int i = 0; i < collection.Count(); i++) { string str1 = collection.ElementAt(i); // do your stuff } 

You might also need this method :-)

+26
Feb 18 '13 at 14:15
source share
 foreach (var element in instanceOfAClassThatImplelemntIEnumerable) { } 
+5
Oct 07 '09 at 16:49
source share



All Articles