简体   繁体   中英

Convert IEnumerable<byte[]> to byte[]

 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[] .

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.

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

What about ToArray extension method?

byte[] array = r.SelectMany(a => a).ToArray();

Are you sure that's what you want to do? This code already returns a byte array:

Encoding.GetEncoding("iso-8859-1").GetBytes(s);

In any case, if you want to convert the enumeration to an array, you would do so like this:

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

EDIT

After your edit, I see I've misunderstood what you're trying to accomplish. If I understand correctly now, you're trying to get a byte array containing concatenated strings in tempResult? I would so it like this:

var concatenated = String.Join("", tempResult.ToArray());    
var byteArray = Encoding.GetEncoding("iso-8859-1").GetBytes(concatenated);

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