Last active
February 23, 2022 12:04
-
-
Save Tornhoof/beb8273fd7bdbb972dde486351f5bb00 to your computer and use it in GitHub Desktop.
List Pattern Slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/#c-11-preview-list-patterns | |
// It's not middle, it's [1..^1], middle is only correct for 3 elements | |
// which could be assumed from https://github.com/dotnet/csharplang/blob/main/proposals/list-patterns.md because the examples | |
// simply do not include anything above 3 elements. | |
Console.WriteLine(CaptureSlice(new int[]{1,2,3})); | |
Console.WriteLine(CaptureSlice(new int[] { 1, 2, 3,4})); | |
Console.WriteLine(CaptureSlice(new int[] { 1, 2, 3, 4, 5 })); | |
Console.WriteLine(CaptureSlice(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 })); | |
Console.ReadLine(); | |
static string CaptureSlice(int[] values) | |
=> values switch | |
{ | |
[1, .. var middle, _] => $"Middle {String.Join(", ", middle)}" | |
}; | |
Output is: | |
Middle 2 | |
Middle 2, 3 | |
Middle 2, 3, 4 | |
Middle 2, 3, 4, 5, 6, 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment