.NET Documentation > API Reference > System.Linq
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source)
Returns the elements of the specified sequence or the type's default value in a singleton collection if the sequence is empty.
source
IEnumerable<TSource>
An IEnumerable<TSource>
to return a default value from if it is empty.
IEnumerable<TSource>
An IEnumerable<TSource>
that contains elements from the source
sequence or the default value for the TSource
type if the sequence is empty.
If the input sequence source
is empty, this method returns a new IEnumerable<TSource>
that contains only the default value for the generic type TSource
. The default value is null
for reference types and 0
for numeric types.
If the input sequence source
is not empty, this method returns the original sequence unchanged.
// C# Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int>();
// numbers is empty, so DefaultIfEmpty will return a collection with the default value of int (0)
IEnumerable<int> result1 = numbers.DefaultIfEmpty();
Console.WriteLine(string.Join(", ", result1)); // Output: 0
List<string> words = new List<string>();
// words is empty, so DefaultIfEmpty will return a collection with the default value of string (null)
IEnumerable<string> result2 = words.DefaultIfEmpty();
Console.WriteLine(result2.FirstOrDefault() == null ? "null" : result2.FirstOrDefault()); // Output: null
List<int> someNumbers = new List<int> { 1, 2, 3 };
// someNumbers is not empty, so DefaultIfEmpty will return the original collection
IEnumerable<int> result3 = someNumbers.DefaultIfEmpty();
Console.WriteLine(string.Join(", ", result3)); // Output: 1, 2, 3
}
}
There is an overload of DefaultIfEmpty
that allows you to specify a custom default value:
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
// C# Example with custom default value
using System;
using System.Collections.Generic;
using System.Linq;
public class ExampleWithDefault
{
public static void Main()
{
List<int> emptyList = new List<int>();
// If the list is empty, use -1 as the default value
IEnumerable<int> result = emptyList.DefaultIfEmpty(-1);
Console.WriteLine(string.Join(", ", result)); // Output: -1
List<int> populatedList = new List<int> { 5, 10 };
// populatedList is not empty, so the default value is ignored
IEnumerable<int> result2 = populatedList.DefaultIfEmpty(-1);
Console.WriteLine(string.Join(", ", result2)); // Output: 5, 10
}
}