Search code examples
c#arraystype-conversionreadonly-collection

C# convert ReadOnlyCollection<int> to byte[] array


Given a read only collection of ints, how do I convert it to a byte array?

ReadOnlyCollection<int> collection = new List<int> { 118,48,46,56,46,50 }.AsReadOnly(); //v0.8.2

What will an elegant way to convert 'collection' to byte[] ?


Solution

  • You can use LINQ's Select method to cast each element from int to byte. This will give you an IEnumerable<byte>. You can then use the ToArray() extension method to convert this to a byte[].

    collection.Select(i => (byte)i).ToArray();
    

    If you don't want to use LINQ then you can instantiate the array and use a for loop to iterate over the collection instead, assigning each value in the array.

    var byteArray = new byte[collection.Count];
    
    for (var i = 0; i < collection.Count; i++)
    {
        byteArray[i] = (byte)collection[i];
    }