Skip to content

Instantly share code, notes, and snippets.

@rossmurray
Last active August 29, 2015 13:56
Show Gist options
  • Save rossmurray/9024979 to your computer and use it in GitHub Desktop.
Save rossmurray/9024979 to your computer and use it in GitHub Desktop.
Infinity() and TakeWhile() as a stream, instead of a while loop.
void Main()
{
var records = GetRecordStream();
foreach (var record in records)
{
SaveRecord(record);
}
}
private IEnumerable<string> GetRecordStream()
{
return Infinity<int>().Select(x => ReadNextRecord()).TakeWhile(x => x != null);
}
private IEnumerable<T> Infinity<T>()
{
return new[] { default(T) }.Cycle();
}
public static class Extensions
{
public static IEnumerable<T> Cycle<T>(this IEnumerable<T> source)
{
while (true)
foreach (var i in source)
yield return i;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment