Skip to content

Instantly share code, notes, and snippets.

@Tornhoof
Last active February 23, 2022 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tornhoof/beb8273fd7bdbb972dde486351f5bb00 to your computer and use it in GitHub Desktop.
Save Tornhoof/beb8273fd7bdbb972dde486351f5bb00 to your computer and use it in GitHub Desktop.
List Pattern Slice
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