Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable<byte[]> to byte[]

Tags:

c#

linq

 var  r = from s in tempResult    
          select Encoding.GetEncoding("iso-8859-1").GetBytes(s);

I understand, this returns IEnumerable<byte[]>, but I looking for LINQ way to convert the whole IEnumerable<byte[]> to byte[].

like image 211
Sandeep Avatar asked Aug 12 '11 18:08

Sandeep


1 Answers

None of the answers provided so far will work, because they will convert the IEnumerable<byte[]> to byte[][]. If your goal is to take all of the arrays in the enumerable and produce one big array, try this:

byte[] result = r.SelectMany(i => i).ToArray();

See this ideone example.


Note that this is not the most efficient way to do this. It would be faster to convert the original query result to a list, then compute the sum of the array lengths. Once that is done, you can allocate the final array immediately, then make one more pass over the result list and copy each result array's contents into the larger array.

The above LINQ query definitely makes this task easy, but it will not be fast. If this code becomes a bottleneck in the application, consider rewriting it this way.


I might as well provide an example of a more efficient implementation:

public static T[] JoinArrays<T>(this IEnumerable<T[]> self)
{
    if (self == null)
        throw new ArgumentNullException("self");

    int count = 0;

    foreach (var arr in self)
        if (arr != null)
            count += arr.Length;

    var joined = new T[count];

    int index = 0;

    foreach (var arr in self)
        if (arr != null)
        {
            Array.Copy(arr, 0, joined, index, arr.Length);
            index += arr.Length;
        }

    return joined;
}

Note that whatever enumerable you pass in will be enumerated twice, so it would be a good idea to pass in a list or an array instead of a query, if that query is expensive.

like image 112
cdhowie Avatar answered Sep 17 '22 16:09

cdhowie