19

How can I take a List and turn it into a byte array.

I thought there might be some clever LINQ options for it but am unsure eg/List.ForEach

Jon
  • 38,814
  • 81
  • 233
  • 382

2 Answers2

41

Depends on which encoding you want to use to convert the string to a byte[] but here's a sample for ASCII. It can be substituted for pretty much any encoding type

List<string> data = ...
byte[] dataAsBytes = data
  .SelectMany(s => Text.Encoding.ASCII.GetBytes(s))
  .ToArray();
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

with a simple foreach loop:

(pseudocode)

    List<byte[]> bytes = new List<byte[]>();
    ForEach string el in somelist
        {
           byte[] arr;
           System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
           arr = encoding.GetBytes(el);
           bytes.add(arr);
        }
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415