0
0
C Sharp (C#)programming~3 mins

Why First, Single, and their OrDefault variants in C Sharp (C#)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could find exactly the item you want in a list with just one simple command, no matter how big the list is?

The Scenario

Imagine you have a long list of names and you want to find the very first name that starts with the letter 'A'. You start scanning the list one by one, checking each name carefully.

The Problem

Doing this by hand or writing long loops is slow and tiring. You might forget to stop after finding the first match, or your code might crash if no name starts with 'A'. It's easy to make mistakes and waste time.

The Solution

Using First, Single, and their OrDefault variants lets you quickly and safely get the item you want from a list. They handle the searching and errors for you, so your code stays clean and easy to read.

Before vs After
Before
foreach(var name in names) {
  if(name.StartsWith("A")) {
    return name;
  }
}
throw new Exception("No match found");
After
var result = names.FirstOrDefault(name => name.StartsWith("A"));
What It Enables

You can easily and safely pick exactly one item from a collection without writing complex loops or error checks.

Real Life Example

Finding the first available seat in a theater booking system or ensuring there is exactly one user with a specific email address in a database.

Key Takeaways

First gets the first matching item; Single expects exactly one match.

OrDefault versions return a safe default if no match is found, avoiding errors.

These methods simplify searching and make your code safer and cleaner.