These methods help you find one item in a list or collection easily. They make your code simple and clear when you want just one element.
First, Single, and their OrDefault variants in C Sharp (C#)
collection.First(); collection.FirstOrDefault(); collection.Single(); collection.SingleOrDefault();
First() returns the first item and throws an error if none found.
Single() expects exactly one item and throws if zero or more than one found.
var firstName = names.First();
var firstOrDefault = names.FirstOrDefault();
var singleUser = users.Single(u => u.Id == 5);var singleOrDefaultUser = users.SingleOrDefault(u => u.Id == 5);This program shows how to use First, FirstOrDefault, Single, and SingleOrDefault on a list of numbers. It prints the results to the console.
using System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new() { 10, 20, 30, 40 }; int first = numbers.First(); int firstOrDefault = numbers.FirstOrDefault(); int single = numbers.Single(n => n == 20); int singleOrDefault = numbers.SingleOrDefault(n => n == 100); Console.WriteLine($"First: {first}"); Console.WriteLine($"FirstOrDefault: {firstOrDefault}"); Console.WriteLine($"Single (20): {single}"); Console.WriteLine($"SingleOrDefault (100): {singleOrDefault}"); } }
Use First() when you want the first item and expect the list not to be empty.
Use FirstOrDefault() to avoid errors if the list might be empty; it returns default value (like 0 or null).
Single() is strict: it throws if there is not exactly one matching item.
SingleOrDefault() returns default if no match, but throws if more than one match.
First() gets the first item or throws if none.
FirstOrDefault() gets the first item or default if none.
Single() gets the only matching item or throws if zero or many.
SingleOrDefault() gets the only matching item or default if none, throws if many.