lazily enumerate a stream in csharp

Assuming you have a stream of objects to be enumerated in C#, you can lazily enumerate the stream using LINQ and the yield keyword.

For example, let's say you have a collection of integers in a List<int> and want to lazily enumerate the values. You can create a method that returns an IEnumerable<int> and use the yield keyword to lazily enumerate the values from the stream.

main.cs
public static IEnumerable<int> EnumerateInts(Stream stream)
{
    using var reader = new StreamReader(stream);
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if (int.TryParse(line, out var value))
        {
            yield return value;
        }
    }
}
294 chars
13 lines

In this example, the yield return statement allows us to return each value in the stream lazily. This means that the enumeration of the values will only happen when they are requested, rather than all at once.

To use this method, you can simply call it and iterate over the values using a foreach loop or any other LINQ method.

main.cs
using var fileStream = new FileStream("myfile.txt", FileMode.Open);
foreach (var value in EnumerateInts(fileStream))
{
    Console.WriteLine(value);
}
151 chars
6 lines

gistlibby LogSnag