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

2
  • 3
    Whats wrong with a simple for loop? Commented Apr 12, 2011 at 15:50
  • 1 byte[] for each string on the list or a single byte[] that containts all the strings on the list.? Commented Apr 12, 2011 at 15:52

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

if you want new line for each item use .GetBytes(s + Environment.NewLine))
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);
        }

1 Comment

That will give you a List<byte[]> but the OP asked for a byte[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.