在C#中,數組切片是從一個數組中提取連續元素的過程
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int startIndex = 2;
int length = 5;
var slicedArray = array.Skip(startIndex).Take(length).ToArray();
Console.WriteLine("原始數組: " + string.Join(", ", array));
Console.WriteLine("切片后的數組: " + string.Join(", ", slicedArray));
}
}
using System;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int startIndex = 2;
int length = 5;
var slicedArray = new ArraySegment<int>(array, startIndex, length);
Console.WriteLine("原始數組: " + string.Join(", ", array));
Console.WriteLine("切片后的數組: " + string.Join(", ", slicedArray));
}
}
using System;
class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int startIndex = 2;
int length = 5;
var slicedArray = new Span<int>(array, startIndex, length);
Console.WriteLine("原始數組: " + string.Join(", ", array));
Console.WriteLine("切片后的數組: " + string.Join(", ", slicedArray.ToArray()));
}
}
這些示例都可以實現數組切片。根據你的需求和項目的.NET版本,你可以選擇最適合你的方法。