C#数组切片方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

namespace CSharpDemo
{
class CSharpDemo
{
public static void Main(string[] args)
{
Slice sp = new Slice();
sp.Test();
Console.WriteLine();
}
}

public class Slice
{
public void Test()
{
var array = new int[] { 0, 1, 2, 3, 4, 6, 7, 8, 9 };

//C#8.0 .Net Core 3.0
var sub1 = array[0..4];
PrintArray("array[0..4]", sub1);

var sub2 = array[2..^2];
PrintArray("array[2..^2]", sub2);

var sub3 = array[2..^0];
PrintArray("array[2..^0]", sub3);

//ArraySegment不会复制数组
var arraySegment = new ArraySegment<int>(array, 1, 7);
PrintArray("ArraySegment<int>(array, 1, 7)", arraySegment);

//ArraySegment.Slice
var trainingData = arraySegment.Slice(0, 3);
var testingData = arraySegment.Slice(3, 2);
PrintArray("arraySegment.Slice(0, 3)", trainingData);
PrintArray("arraySegment.Slice(3, 2)", testingData);

//Linq
var bar = array.Take(4);
PrintArray("array.Take(4)", bar);

var subset = array.Skip(2).Take(4);
PrintArray("array.Skip(2).Take(4)", subset);

//Array.Copy
int[] dest = new int[4];
Array.Copy(array, 0, dest, 0, 4);
PrintArray("Array.Copy(array, 0, dest, 0, 4)", dest);

//Utilizing ReadOnlySpan<T> or Span<T> to Slice Arrays
var span1 = new ReadOnlySpan<int>(array, 0, 3);
var span2 = new ReadOnlySpan<int>(array, 3, 2);

Console.Write("ReadOnlySpan span1:");
foreach (var record in span1)
Console.Write(record);
Console.WriteLine();
Console.Write("ReadOnlySpan span2:");
foreach (var record in span2)
Console.Write(record);
}

public void PrintArray(string type, IEnumerable<int> ieArray)
{
Console.WriteLine($"{type} -> {string.Join("|", ieArray)}");
}
}
}

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
array[0..4] -> 0|1|2|3
array[2..^2] -> 2|3|4|6|7
array[2..^0] -> 2|3|4|6|7|8|9
ArraySegment<int>(array, 1, 7) -> 1|2|3|4|6|7|8
arraySegment.Slice(0, 3) -> 1|2|3
arraySegment.Slice(3, 2) -> 4|6
array.Take(4) -> 0|1|2|3
array.Skip(2).Take(4) -> 2|3|4|6
Array.Copy(array, 0, dest, 0, 4) -> 0|1|2|3
ReadOnlySpan span1:012
ReadOnlySpan span2:34

参考

https://code-maze.com/csharp-array-slicing/