Is there a good way to enumerate through only a subset of a Collection in C#? That is, I have a collection of a large number of objects (say, 1000), but I\'d like to enumerate
Try the following
var col = GetTheCollection();
var subset = col.Skip(250).Take(90);
Or more generally
public static IEnumerable GetRange(this IEnumerable source, int start, int end) {
// Error checking removed
return source.Skip(start).Take(end - start);
}
EDIT 2.0 Solution
public static IEnumerable GetRange(IEnumerable source, int start, int end ) {
using ( var e = source.GetEnumerator() ){
var i = 0;
while ( i < start && e.MoveNext() ) { i++; }
while ( i < end && e.MoveNext() ) {
yield return e.Current;
i++;
}
}
}
IEnumerable col = GetTheCollection();
IEnumerable range = GetRange(col, 250, 340);