In .NET 3.5 the canonical answer would be to use Take
. Fortunately, you can write this very easily for .NET 2.0:
public static IEnumerable<T> Take<T>(IEnumerable<T> source, int limit)
{
// Error checking omitted
using (IEnumerator<T> iterator = source.GetEnumerator())
{
for (int i = 0; i < limit; i++)
{
if (!iterator.MoveNext())
{
yield break;
}
yield return iterator.Current;
}
}
}
Then you can do:
foreach (SimplifiedFeedItem item in Take(allFeeds, 6))
{
// Do stuff
}
Alternatively, you could just get hold of LINQBridge and have the whole of LINQ to Objects available to you...
The advantage of doing things this way is that when you eventually upgrade to .NET 3.5 or later, you'll have a solution which can be turned into idiomatic LINQ very easily:
foreach (SimplifiedFeedItem item in allFeeds.Take(6))
Note that error checking with iterator blocks is slightly tricky - you need to write a "normal" method which does the argument checking, and then call the iterator separately; otherwise the exception isn't throw until you start iterating.