Search code examples
c#stringlinqbyteconvertall

How do I convert a string array to a byte array using Array ConvertAll?


I can convert string[] to byte[] like in the following code:

 byte[] k = {255, 150, 155, 255, 255, 255, 255, 255, 255, 255, 55, 55, 15, 55, 155, 55};
 string st = BitConverter.ToString(Array.ConvertAll(k, Convert.ToByte));     
 byte[] kk = new byte[16];
 string[] sts = st.Split('-');            
 for (int i = 0; i < 16; i++)
 {
    kk[i] = Convert.ToByte(sts[i], 16);
 }

But I can't do the same with LINQ like in the code below:

Array.ConvertAll(sts,item=>(byte) Convert.ToByte(item, 16))

How do I make this work in LINQ?

Why is it not working in the "Immediate Window" of Visual Studio?

Lambda expressions do not work in "Immediate" and "Watch" windows.


Solution

  • Your code does work. Maybe you forgot a semicolon:

     var a = Array.ConvertAll(sts, s => Convert.ToByte(s, 16));