Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Linq FirstorDefault Method
The FirstOrDefault() method in C# LINQ returns the first element of a sequence, or a default value if the sequence is empty or no element matches the specified condition. This method is useful when you need to safely retrieve the first element without throwing an exception.
Syntax
Following is the syntax for using FirstOrDefault() −
// Without condition public static T FirstOrDefault<T>(this IEnumerable<T> source); // With condition public static T FirstOrDefault<T>(this IEnumerable<T> source, Func<T, bool> predicate);
Parameters
-
source − The sequence to return the first element from.
-
predicate (optional) − A function to test each element for a condition.
Return Value
Returns the first element that satisfies the condition or the default value for the type if no such element is found. For reference types, the default is null. For value types like int, it's 0, and for bool, it's false.
Using FirstOrDefault() with Empty Collection
When working with an empty collection, FirstOrDefault() returns the default value for the type instead of throwing an exception −
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
List<double> val = new List<double> { };
double d = val.FirstOrDefault();
Console.WriteLine("Default Value = " + d);
if (d == 0.0D) {
d = 0.1D;
}
Console.WriteLine("Default Value changed = " + d);
}
}
The output of the above code is −
Default Value = 0 Default Value changed = 0.1
Using FirstOrDefault() with Non-Empty Collection
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> numbers = new List<int> { 5, 10, 15, 20, 25 };
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
int firstNumber = numbers.FirstOrDefault();
string firstName = names.FirstOrDefault();
Console.WriteLine("First number: " + firstNumber);
Console.WriteLine("First name: " + firstName);
}
}
The output of the above code is −
First number: 5 First name: Alice
Using FirstOrDefault() with Condition
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
List<int> numbers = new List<int> { 1, 3, 5, 8, 12, 15 };
int firstEven = numbers.FirstOrDefault(x => x % 2 == 0);
int firstGreaterThan20 = numbers.FirstOrDefault(x => x > 20);
Console.WriteLine("First even number: " + firstEven);
Console.WriteLine("First number > 20: " + firstGreaterThan20);
}
}
The output of the above code is −
First even number: 8 First number > 20: 0
Comparison with First() Method
| FirstOrDefault() | First() |
|---|---|
| Returns default value if no element found | Throws InvalidOperationException if no element found |
| Safe to use with empty collections | Will throw exception with empty collections |
| Better for scenarios where element might not exist | Better when you're certain element exists |
Conclusion
The FirstOrDefault() method provides a safe way to retrieve the first element from a collection without throwing exceptions. It returns the default value for the type when no matching element is found, making it ideal for scenarios where the absence of elements is a valid case.
