Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Last active June 6, 2025 17:49
Show Gist options
  • Save jasonsperske/b3055ad3ac47214828909312f41f9539 to your computer and use it in GitHub Desktop.
Save jasonsperske/b3055ad3ac47214828909312f41f9539 to your computer and use it in GitHub Desktop.
take function in c#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static IEnumerable<T> take<T>(IEnumerable<T> things, int size)
{
using (var iter = things.GetEnumerator())
{
var i = 0;
while (iter.MoveNext() && i < size)
{
yield return iter.Current;
i++;
}
}
}
public static IEnumerable<int> generate(int size)
{
var i = 0;
while (true && i < size)
{
yield return i;
i++;
}
}
public static void Main()
{
// Show it taking various enumerable datatypes
Console.WriteLine(string.Join(",", take(new List<string> { "test1", "test2", "test3", "test4", "test5" }, 3)));
// test1,test2,test3
Console.WriteLine(string.Join(",", take(new string[] { "test1", "test2", "test3", "test4", "test5" }, 2)));
// test1,test2
Console.WriteLine(string.Join(",", take(Enumerable.Range(0, 1001), 4)));
// 0,1,2,3
Console.WriteLine(string.Join(",", take(generate(100), 10)));
// 0,1,2,3,4,5,6,7,8,9
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment