Enumerate through a subset of a Collection in C#?

后端 未结 6 1475
粉色の甜心
粉色の甜心 2021-02-08 01:12

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

6条回答
  •  抹茶落季
    2021-02-08 01:53

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

提交回复
热议问题