Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Stream to IEnumerable. If possible when "keeping laziness"

Tags:

c#

I recieve a Stream and need to pass in a IEnumerable to another method.

public static void streamPairSwitchCipher(Stream someStream)
{
    ...
    someStreamAsIEnumerable = ...
    IEnumerable returned = anotherMethodWhichWantsAnIEnumerable(someStreamAsIEnumerable);
    ...
}

One way is to read the entire Stream, convert it to an Array of bytes and pass it in, as Array implements IEnumerable. But it would be much nicer if I could pass in it in such a way that I don't have to read the entire Stream before passing it in.

public static IEnumerable<T> anotherMethodWhichWantsAnIEnumerable<T>(IEnumerable<T> p) {
    ... // Something uninteresting
}
like image 316
Deleted Avatar asked Apr 13 '10 14:04

Deleted


1 Answers

This one reads your stream byte by byte 'on demand':

public static IEnumerable<byte> streamAsIEnumerable(Stream stream)
{
    if (stream == null)
        throw new ArgumentNullException("stream");

    for (; ; )
    {
        int readbyte = stream.ReadByte();
        if (readbyte == -1)
            yield break;
        yield return (byte)readbyte;
    }
}

Or even shorter, and not raising an exception if the stream is null, but just yielding nothing:

public static IEnumerable<byte> streamAsIEnumerable(Stream stream)
{
    if (stream != null)
        for (int i = stream.ReadByte(); i != -1; i = stream.ReadByte())
            yield return (byte)i;
}
like image 59
Philip Daubmeier Avatar answered Oct 17 '22 21:10

Philip Daubmeier