通过收集在C#中的一个子集枚举? [英] Enumerate through a subset of a Collection in C#?

查看:190
本文介绍了通过收集在C#中的一个子集枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有只通过在C#集合的子集枚举的好办法?也就是说,我有大量的对象(比如1000)的集合,但我想只通过元素250列举 - 340是否有一个很好的方式来获得集合的子集的枚举器,无使用另一个集合

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 through only elements 250 - 340. Is there a good way to get an Enumerator for a subset of the collection, without using another Collection?

编辑:?应该提到,这是使用.NET Framework 2.0的

should have mentioned that this is using .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);
}

修改 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);

这篇关于通过收集在C#中的一个子集枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆