Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active February 26, 2025 22:39
Show Gist options
  • Save karenpayneoregon/27543b165baf05bd5c3f4bd2f49a7699 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/27543b165baf05bd5c3f4bd2f49a7699 to your computer and use it in GitHub Desktop.
C# 11 list pattern

About

Imagine a developer needs to read data were each line of a list or a list of list needs to validate that the first element and last element must be specific values.

In this case, first element a 1 and the last a 4.

Data

[1, 4]
[1, 2, 3]
[1, 2, 3, 4]
[0, 2, 3, 4]
[1, 2, 3, 5, 4]

Results

0  is match    Not a match
1  is match    Not a match
2  is match    Match
3  is match    Not a match
4  is match    Match

See List patterns docs.

using System.Text.Json;
namespace TODO;
class Samples
{
public static void IntegerListMatch()
{
List<List<int>> list =
[
[1, 4],
[1, 2, 3],
[1, 2, 3, 4],
[0, 2, 3, 4],
[1, 2, 3, 5 ,4],
];
Console.WriteLine("Data");
foreach (var sublist in list)
{
Console.WriteLine($"[{string.Join(", ", sublist)}]");
}
Console.WriteLine();
foreach (var (index, item) in list.Index())
{
Console.WriteLine($"{index,-2} is match {(item is [1, 2, 3, .., 4] ? "Match" : "Not a match")}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment