如何循环访问支持 IEnumable 的集合?

如何循环访问支持 IEnumable 的集合?

209463 次浏览

每个人都有一个常客就可以了:

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


}

除了已经推荐的使用 foreach循环的方法之外,我还想提到实现 IEnumerable的任何对象也通过 GetEnumerator方法提供 IEnumerator接口。尽管这种方法通常不是必需的,但是它可以用于手动迭代集合,并且在为集合编写自己的扩展方法时特别有用。

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

一个主要的例子是,当您想要在 同时有两个序列上迭代时,使用 foreach循环是不可能的。

甚至是非常经典的老式方法

using System.Collections.Generic;
using System.Linq;
...


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
}

也许你也会喜欢这个方法: -)

如果您喜欢简短的代码,也可以尝试使用扩展:

namespace MyCompany.Extensions
{
public static class LinqExtensions
{
public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> actor) { foreach (var x in source) { actor(x); } }
}
}

This will generate some overhead, for the sake of having stuff inline.

collection.Where(item => item.IsReady).ForEach(item => item.Start());