I want something similar to String.Join(separator_string, list_of_strings)
but for byte arrays.
I need it because I am implementing a file format writer, and the specification says
"Each annotation must be encoded as UTF-8 and separated by the ASCII byte
20
."
Then I would need something like:
byte separator = 20;
List<byte[]> encoded_annotations;
joined_byte_array = Something.Join(separator, encoded_annotations);
I don't believe there's anything built in, but it's easy enough to write. Here's a generic version, but you could make it do just byte arrays easily enough.
public static T[] Join<T>(T separator, IEnumerable<T[]> arrays)
{
// Make sure we only iterate over arrays once
List<T[]> list = arrays.ToList();
if (list.Count == 0)
{
return new T[0];
}
int size = list.Sum(x => x.Length) + list.Count - 1;
T[] ret = new T[size];
int index = 0;
bool first = true;
foreach (T[] array in list)
{
if (!first)
{
ret[index++] = separator;
}
Array.Copy(array, 0, ret, index, array.Length);
index += array.Length;
first = false;
}
return ret;
}
See more on this question at Stackoverflow