Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字节[]返回列表<;int>;_C# - Fatal编程技术网

C#字节[]返回列表<;int>;

C#字节[]返回列表<;int>;,c#,C#,我有一个列表,我正在转换为字节[],如下所示: List<int> integerList = new List<int>(); integerList.Add(1); integerList.Add(2); integerList.Add(3); byte[] bytes = integerList.SelectMany(BitConverter.GetBytes).ToArray(); List integerList=newlist(); 整数列表。添加(1)

我有一个列表,我正在转换为字节[],如下所示:

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

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

byte[] bytes = integerList.SelectMany(BitConverter.GetBytes).ToArray();
List integerList=newlist();
整数列表。添加(1);
整数列表。添加(2);
整数列表。添加(3);
byte[]bytes=integerList.SelectMany(BitConverter.GetBytes.ToArray();
如何将其转换回列表

byte[] is an IEnumerable; LINQ's ToList() extension method should do it.
编辑:如果需要int的列表:

bytes.Select((b) => (int)b).toList();

多种方法之一(LINQ方法):

次要更新:

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

静态列表ToListOf(字节[]数组,Func位转换器)
{
var size=Marshal.SizeOf(typeof(T));
返回可枚举的.范围(0,数组.长度/大小)
.选择(i=>位转换器(数组,i*大小))
.ToList();
}
用法:

var originalList = ToListOf<int>(bytes, BitConverter.ToInt32);
var originalList=ToListOf(字节,位转换器.ToInt32);

是;这不是你要问的吗?是的,这只是产生一个字节列表,只是测试了它。@Mellvar:我没有问这个问题,但我不相信他们也在问这个问题。他们将整数列表转换为字节数组,因此我认为他们希望从任何建议的解决方案中得到相同整数的列表。@mellvarnope:)。我正试图将此列表放入azure队列,它要求我将其作为bytearray(或字符串)放入,但我不想这样做。您最近的代码返回一个包含12个整数的列表,其中每4个整数都是序列中的正确整数(1,0,0,0,2,0,0,0,0,3,0,0,0)@Nate:这很好,否则做起来效率极低:)如果这是您看到的,那么您的字节数组必须是12个元素的长度,这是一个很好的答案。问题是Nate试图解析的整数大小不一致,不一致为4字节。更新的答案:添加了通用版本,可用于任何类型
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();
}
var originalList = ToListOf<int>(bytes, BitConverter.ToInt32);