1

I have a Listof objects that I would like to convert to a byte[]

My List is defined like this:

List<object> objects = new List<object>
{
     "obj1", "obj2", "obj2"
};

Is it possible to convert this list to a byte[] in some clean way? The list only contains base64 strings

All help is appreciated

2
  • 3
    Then why isn't objects a List<string>? Commented Mar 19, 2012 at 18:07
  • What do you mean by "clean"? Have you considered using one of the serialization mechanisms that the .NET framework provides, e.g. binary or SOAP formatting? Commented Mar 19, 2012 at 18:08

2 Answers 2

4

Piece of cake:

objects.Select(s => Convert.FromBase64String(s)).SelectMany(i => i).ToArray();

If objects is really a List<Object> as @AustinSalonen points out, as opposed to a List<String>, you need to make sure that you only have strings first:

objects.OfType<String>().Select(s => Convert.FromBase64String(s)).SelectMany(i => i).ToArray();

or cast:

objects.Cast<String>().Select(s => Convert.FromBase64String(s)).SelectMany(i => i).ToArray();
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your answer. Yes I would like all of the data into one big array.
Thank your very much. I have one last question, what about if the items in the last arent base64 string? If it isn't much truble I would like to se a solution for non base64 items. Is it possible?
If not base-64 then what are they? Your original question very specifically stated "The list only contains base64 strings"
Very sorry for the confusion. The items could be normal strings.
What format should be used for converting them into bytes? UTF-8? ASCII? Base-64 has special meaning- it means that the characters are an encoded representation of a specific sequence of bytes. ASCII means something else. UTF-8 (typically called unicode) means something else again. You need to be specific.
|
1

This should work for strings:

System.Text.Encoding enc = System.Text.Encoding.ASCII;  // Choose the right encoding here
List<byte[]> list = objects.Select(o=>enc.GetBytes(o.ToString()).ToList();

Comments

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.