I tried to use the List.ConvertAll method and failed. What I am trying to do is convert a List<Int32>
to byte[]
I copped out and went this route, but I need to figure out the ConvertAll method...
List<Int32> integers...
internal byte[] GetBytes()
{
List<byte> bytes = new List<byte>(integers.Count * sizeof(byte));
foreach (Int32 integer in integers)
bytes.AddRange(BitConverter.GetBytes(integer));
return bytes.ToArray();
}
How about
totally untested BTW, but seems reasonable.
This should actually give you an Array of arrays of bytes...which may or may not be what you need. If you want to collapse it into a single array, you can use
SelectMany
The ConvertAll method is flawed because it expects there to be a 1:1 mapping from the source to the destination. This is not true when converting integers to bytes. You are much better off going with a solution such as what @SLaks has suggested with the SelectMany extension method.
To use the ConvertAll method you can do the following...
Assuming that you have a list of ints that are really byte values and you do not actually want the bytes required to make up an int, i.e.
byte[][]
:... to convert ...
or you could use an anonymous delegate...
Since you don't want a
byte[][]
where each integer maps to an array of four bytes, you cannot callConvertAll
. (ConvertAll
cannot perform a one-to-many conversion)Instead, you need to call the LINQ
SelectMany
method to flatten each byte array fromGetBytes
into a singlebyte[]
: