在 C# 中是否有一种好方法可以仅枚举 Collection 的子集?也就是说,我有大量对象的集合(例如 1000 个),但我只想枚举元素 250 - 340。有没有一种好方法可以获取集合子集的枚举器,而无需使用另一个集合?
编辑:应该提到这是使用 .NET Framework 2.0。
尝试以下操作
var col = GetTheCollection();
var subset = col.Skip(250).Take(90);
或者更一般地说
public static IEnumerable<T> GetRange(this IEnumerable<T> source, int start, int end) {
// Error checking removed
return source.Skip(start).Take(end - start);
}
EDIT2.0解决方案
public static IEnumerable<T> GetRange<T>(IEnumerable<T> 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<Foo> col = GetTheCollection();
IEnumerable<Foo> range = GetRange(col, 250, 340);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)