Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Use List Patterns for Powerful Array and List Matching

- 05.06.26 - ErcanOPAK

📋 Match Arrays Like Prolog

Match first element, last element, empty list — all with pattern matching. List patterns make array processing declarative.

📝 Basic Patterns

int[] numbers = [1, 2, 3, 4, 5];

// Match first two elements
if (numbers is [1, 2, ..]) {
    Console.WriteLine("Starts with 1,2");
}

// Match last two elements
if (numbers is [.., 4, 5]) {
    Console.WriteLine("Ends with 4,5");
}

// Extract middle elements
if (numbers is [1, .. var middle, 5]) {
    Console.WriteLine($"Middle: {string.Join("", "", middle)}"); // 2,3,4
}

// Empty check
if (numbers is []) {
    Console.WriteLine("Empty array");
}

🎯 Switch with List Patterns

string GetCommandType(string[] args) => args switch
{
    [] => "No arguments",
    ["help"] => "Help command",
    ["build"] => "Build command",
    ["test", ..] => "Test command with arguments",
    ["run", var project, ..] => $"Run project: {project}",
    ["-v" or "--version"] => "Version command",
    [_, _] => "Exactly two arguments",
    [_, .., _] => "At least two arguments",
    _ => "Unknown command"
};

// Nested list patterns
int[][] matrix = [[1, 2], [3, 4], [5, 6]];
if (matrix is [[1, 2], ..]) {
    Console.WriteLine("First row is 1,2");
}

✅ Real-World Example

public static string ParseLogLevel(string[] parts) => parts switch
{
    // ERROR: Database connection failed
    ["ERROR", "Database", ..] => "Database error",
    
    // WARNING: Low disk space on /dev/sda
    ["WARNING", "Disk", .. var details] => $"Disk warning: {string.Join(" ", details)}",
    
    // INFO: User 123 logged in
    ["INFO", "User", var userId, "logged in"] => $"User {userId} login",
    
    // Any error with timestamp [2024-01-15 ERROR] 
    [var timestamp, "ERROR", ..] when timestamp.StartsWith("[") => $"Error at {timestamp}",
    
    // Default
    _ => "Unknown log entry"
};

// Usage in parser
string[] logParts = ["ERROR", "Database", "connection", "timeout"];
string result = ParseLogLevel(logParts); // "Database error"

💡 Benefits

  • No more index out of bounds checks (pattern handles length)
  • Declarative parsing of command-line arguments
  • Destructuring with .. var captures rest of array
  • Works with any type that has length/indexer

“Replaced 30 lines of CLI argument parsing with 10 lines of list patterns. No more manual bounds checks. List patterns make array handling elegant and safe.”

— CLI Tool Developer

Related posts:

Add default value to Devex Grid Columns in C#

Pattern Matching switch

How to use SQL RAISEERROR() messages in C#

Post Views: 5

Post navigation

C#: Use Generic Math for Mathematical Algorithms on Any Numeric Type
Visual Studio: Shift + Right Click to Copy Full File Path

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • Average of all values in a column that are not zero in SQL (538)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (505)
  • Find numbers with more than two decimal places in SQL (454)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com