Pau*_*ier 11 c# collections enumeration subset .net-2.0
有没有一种很好的方法来枚举C#中只有一个Collection的子集?也就是说,我有一个大量对象的集合(比如1000),但是我想仅枚举元素250-340.有没有一个很好的方法来获取集合的子集的枚举器,没有使用另一个系列?
编辑:应该提到这是使用.NET Framework 2.0.
Jar*_*Par 36
请尝试以下方法
var col = GetTheCollection();
var subset = col.Skip(250).Take(90);
Run Code Online (Sandbox Code Playgroud)
或者更一般地说
public static IEnumerable<T> GetRange(this IEnumerable<T> source, int start, int end) {
// Error checking removed
return source.Skip(start).Take(end - start);
}
Run Code Online (Sandbox Code Playgroud)
编辑 2.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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5237 次 |
| 最近记录: |