C#byte []返回List <int>

Nat*_*ate 6 c#

我有一个List,我正在转换为byte [],如下所示:

List<int> integerList = new List<int>();

integerList.Add(1);
integerList.Add(2);
integerList.Add(3);

byte[] bytes = integerList.SelectMany(BitConverter.GetBytes).ToArray();
Run Code Online (Sandbox Code Playgroud)

如何将其转换回List?

max*_*max 16

其中一种方法(LINQ):

var originalList = Enumerable.Range(0, bytes.Length / 4)
                             .Select(i => BitConverter.ToInt32(bytes, i * 4))
                             .ToList();
Run Code Online (Sandbox Code Playgroud)

次要更新:

您还可以编写一个方便的通用版本(以防您需要使用其他类型):

static List<T> ToListOf<T>(byte[] array, Func<byte[], int, T> bitConverter)
{
    var size = Marshal.SizeOf(typeof(T));
    return Enumerable.Range(0, array.Length / size)
                     .Select(i => bitConverter(array, i * size))
                     .ToList();
}
Run Code Online (Sandbox Code Playgroud)

用法:

var originalList = ToListOf<int>(bytes, BitConverter.ToInt32);
Run Code Online (Sandbox Code Playgroud)