How to loop through a collection that supports IEnumerable?

北战南征 提交于 2019-12-29 13:35:39

问题


How to loop through a collection that supports IEnumerable?


回答1:


A regular for each will do:

foreach (var item in collection)
{
    // do your stuff   
}



回答2:


Along with the already suggested methods of using a foreach loop, I thought I'd also mention that any object that implements IEnumerable also provides an IEnumerator interface via the GetEnumerator method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.

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

A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach loop.




回答3:


or even a very classic old fashion method

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

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

maybe you would like this method also :-)




回答4:


foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}


来源:https://stackoverflow.com/questions/1532814/how-to-loop-through-a-collection-that-supports-ienumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!