3
byte[] result = memStream.ToArray();                              
memStream.Close();
byte[] temp = result.Take(255);
var str = System.Text.Encoding.Default.GetString(temp);

The above fails on the result.Take(255); line. It says I can't convert IEnumerable to byte[], and asks if I'm missing a cast.

I'm new to C#, not exactly sure what to do.

GSerg
  • 76,472
  • 17
  • 159
  • 346
MrDysprosium
  • 489
  • 9
  • 20

2 Answers2

7

Take() returns an enumerator object that executes when you enumerate it:

enter image description here

That's not an array, so you can't assign it to a reference to a byte array. However, with LINQ, you can take any sequence and convert it to an array of the appropriate type by calling its ToArray() method:

byte[] temp = result.Take(255).ToArray();

ToArray() enumerates the result from Take(255), puts the results in a new array, and returns the array.

It's a little confusing because you can enumerate an array just like you can enumerate the thing you get from Take(255) -- but you can enumerate a lot of things. That's just one behavior they have in common, but they're actually very different objects.

You could assign either one to IEnumerable<byte>:

IEnumerable<byte> a = result.Take(255);
IEnumerable<byte> b = result.Take(255).ToArray();

...because that's one thing they really have in common.

1

The reason your code is giving an error is because .Take(result) returns an IEnumerable<byte> type and you're trying to assign it to a byte[] array. .Take() is a LINQ method and this is typically the way all LINQ methods work for the purpose of chaining (e.g. result.Skip(5).Take(10)).

The .ToArray() method takes an IEnumerable<T> result and turns it into a T[]. So adding .ToArray() to your line will fix your problem:

byte[] temp = result.Take(255).ToArray();

Instead of using .Take() and then creating another array, you'll probably find this more performant:

byte[] temp = new byte[255]
Array.Copy(result, temp, 255);

The reason is because .ToArray() has no idea how big the resulting array will need to be, so it has to just pick some relatively small size and as more items get read in, it has to resize to expand capacity. This can occur dozens of times, depending on the number of items, before the array is large enough to store all of the items.

itsme86
  • 19,266
  • 4
  • 41
  • 57