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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With