在C#中,數(shù)組切片是從一個數(shù)組中提取連續(xù)元素的過程
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("原始數(shù)組: " + string.Join(", ", array));
Console.WriteLine("切片后的數(shù)組: " + 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("原始數(shù)組: " + string.Join(", ", array));
Console.WriteLine("切片后的數(shù)組: " + 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("原始數(shù)組: " + string.Join(", ", array));
Console.WriteLine("切片后的數(shù)組: " + string.Join(", ", slicedArray.ToArray()));
}
}
這些示例都可以實現(xiàn)數(shù)組切片。根據(jù)你的需求和項目的.NET版本,你可以選擇最適合你的方法。