C# 如何遍历支持 IEnumerable 的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1532814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through a collection that supports IEnumerable?
提问by mrblah
How to loop through a collection that supports IEnumerable?
如何遍历支持 IEnumerable 的集合?
采纳答案by Fredrik M?rk
A regular for each will do:
每个人的常规都会做:
foreach (var item in collection)
{
// do your stuff
}
回答by Darin Dimitrov
foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{
}
回答by Noldorin
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.
除了已经建议的使用foreach
循环的方法之外,我想我还要提到任何实现的对象IEnumerable
也IEnumerator
通过该GetEnumerator
方法提供一个接口。尽管此方法通常不是必需的,但可用于手动迭代集合,并且在编写自己的集合扩展方法时特别有用。
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.
一个主要的例子是当你想同时迭代两个序列时,这是foreach
循环所不可能的。
回答by Alexa Adrian
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 :-)
也许你也喜欢这种方法:-)