C#中的数组切片 [英] Array slices in C#
问题描述
你是怎么做到的?给定一个字节数组:
How do you do it? Given a byte array:
byte[] foo = new byte[4096];
如何将数组的前 x 个字节作为单独的数组获取?(具体来说,我需要它作为 IEnumerable
)
How would I get the first x bytes of the array as a separate array? (Specifically, I need it as an IEnumerable<byte>
)
这是为了使用 Socket
s.我认为最简单的方法是数组切片,类似于 Perls 语法:
This is for working with Socket
s. I figure the easiest way would be array slicing, similar to Perls syntax:
@bar = @foo[0..40];
这会将前 41 个元素返回到 @bar
数组中.C# 中是否有我遗漏的东西,或者我应该做的其他事情?
Which would return the first 41 elements into the @bar
array. Is there something in C# that I'm just missing, or is there some other thing I should be doing?
LINQ 对我来说是一个选择(.NET 3.5),如果有帮助的话.
LINQ is an option for me (.NET 3.5), if that helps any.
推荐答案
数组是可枚举的,所以你的 foo
已经是一个 IEnumerable
本身.只需使用 LINQ 序列方法,例如 Take()
得到你想要的(不要忘记在 using System.Linq;
中包含 Linq
命名空间):>
Arrays are enumerable, so your foo
already is an IEnumerable<byte>
itself.
Simply use LINQ sequence methods like Take()
to get what you want out of it (don't forget to include the Linq
namespace with using System.Linq;
):
byte[] foo = new byte[4096];
var bar = foo.Take(41);
如果你真的需要一个来自任何 IEnumerable
值的数组,你可以使用 ToArray()
方法.这里似乎不是这种情况.
If you really need an array from any IEnumerable<byte>
value, you could use the ToArray()
method for that. That does not seem to be the case here.
这篇关于C#中的数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!