Peter Peter - 1 month ago 45
C# Question

How to convert IEnumerable to byte array

I need to combine several arrays to one. I've found that seems to be a good way to do this:

IEnumerable<byte> Combine(byte[] a1, byte[] a2, byte[] a3)
{
foreach (byte b in a1)
yield return b;
foreach (byte b in a2)
yield return b;
foreach (byte b in a3)
yield return b;
}


However, I'm not well familiar with
IEnumerable
. How do I convert the result back to
byte[]
so I could work further with it?

Thank you.

Answer

Instead of iterating them just linq's .Concat:

var joint = a1.Concat(a2).Concat(a3);

If you want to return it as an array:

joint.ToArray();