简体   繁体   中英

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.

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();

I'd write it like this:

IEnumerable<T> Combine<T>(params IEnumerable<T>[] stuff)
{
    return stuff.SelectMany(a => a);
}

And merge to a single array like this:

var a = new byte[] { 0, 1, 2 };
var b = new byte[] { 0, 1, 2 };
var c = new List<byte> { 0, 1, 2 };

var merged = Combine(a, b, c).ToArray();

Notice the joker in the deck -- no need to restrict input to arrays. Any array T[] is an IEnumerable<T> , but so are lots of other things.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM