Converting a list of ints to a byte array

后端 未结 4 2020
旧巷少年郎
旧巷少年郎 2021-01-17 12:26

I tried to use the List.ConvertAll method and failed. What I am trying to do is convert a List to byte[]

I copped out and went

4条回答
  •  执念已碎
    2021-01-17 13:13

    To use the ConvertAll method you can do the following...

    Assuming that you have a list of ints that are really byte values and you do not actually want the bytes required to make up an int, i.e. byte[][]:

    public static class Utility {
    
       public static byte IntToByte(int i) {
           if(i < 0)
               return (byte)0;
           else if(i > 255)
               return (byte)255;
           else
               return System.Convert.ToByte(i);
       }
    }
    

    ... to convert ...

    byte[] array = listOfInts.ConvertAll(
                        new Converter(Utility.IntToByte) ).ToArray();
    

    or you could use an anonymous delegate...

    byte[] array = listOfInts.ConvertAll( new Converter(
                       delegate(int i) {
                           if(i < 0)
                              return (byte)0;
                           else if(i > 255)
                              return (byte)255;
                           else
                              return System.Convert.ToByte(i);
                       })).ToArray();
    

提交回复
热议问题