Returns the first element of a sequence that satisfies a condition, or a default value if no such element is found.
FirstOrDefault<TSource>(IEnumerable<TSource> source)
Returns the first element of a sequence.
FirstOrDefault<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
Returns the first element of a sequence that satisfies a condition.
source (IEnumerable<TSource>)
An IEnumerable<TSource> to return an element from.
predicate (Func<TSource, bool>)
A function to test each element for a condition.
The first element of the sequence that satisfies the condition, or the default value for the type of the elements in the sequence if no such element is found.
If the type of elements in source is a reference type, the default value is null. If the type of elements is a value type, the default value is the value returned by calling the parameterless constructor of the value type (e.g., 0 for numeric types, false for bool, and null for nullable value types).
The FirstOrDefault method enumerates through the sequence and stops as soon as it finds an element that satisfies the condition. If the sequence is empty or no element satisfies the condition, it returns the default value for the element type.
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Get the first element, or 0 if the list is empty
int firstOrDefaultValue = numbers.FirstOrDefault();
Console.WriteLine($ "FirstOrDefault without predicate: {firstOrDefaultValue}"); // Output: 1
// Get the first element greater than 3, or 0 if none found
int firstGreaterThanThree = numbers.FirstOrDefault(n => n > 3);
Console.WriteLine($ "FirstOrDefault with predicate (n > 3): {firstGreaterThanThree}"); // Output: 4
List<int> emptyList = new List<int>();
int firstInEmpty = emptyList.FirstOrDefault();
Console.WriteLine($ "FirstOrDefault on empty list: {firstInEmpty}"); // Output: 0
int firstGreaterThanTen = numbers.FirstOrDefault(n => n > 10);
Console.WriteLine($ "FirstOrDefault with predicate (n > 10): {firstGreaterThanTen}"); // Output: 0
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
string firstDefaultName = names.FirstOrDefault();
Console.WriteLine($ "FirstOrDefault on string list: {firstDefaultName}"); // Output: Alice
string firstDefaultNullName = null;
List<string> nullNames = new List<string>();
string firstInNullNames = nullNames.FirstOrDefault();
Console.WriteLine($ "FirstOrDefault on null string list: {firstInNullNames ?? "null"}"); // Output: null
}
}