CSharp · Console
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<string> fruits = new() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var e = fruits.GetEnumerator();
var firstThree = e.Take(3);
var nextThree = e.Take(3);
// prints 1, 2, 3
foreach (var x in firstThree)
Console.WriteLine(x);
// also prints 1, 2, 3
foreach (var x in nextThree)
Console.WriteLine(x);
}
}
public static class Extensions
{
public static List<T> Take<T>(this IEnumerator<T> e, int num)
{
List<T> list = new List<T>(num);
int taken = 0;
while (taken < num && e.MoveNext())
{
list.Add(e.Current);
taken++;
}
return list;
}
}