System.Linq.DefaultIfEmpty<TSource>

Overview

Returns the elements of the specified sequence or the type parameter's default value in a singleton collection if the sequence is empty.

Syntax

public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source)
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)

Namespace: System.Linq
Assembly: System.Linq.dll

Parameters

Name Type Description
source IEnumerable<TSource> An IEnumerable<TSource> to return elements from.
defaultValue TSource The value to return in a singleton collection if the source sequence is empty.

Return Value

IEnumerable<TSource>
An IEnumerable<TSource> that contains elements from the input sequence or the specified default value in a singleton collection if the sequence is empty.

Examples

Example 1: Using DefaultIfEmpty with an empty sequence

The following code example demonstrates how to use the DefaultIfEmpty method on an empty sequence.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        // Create an empty list of integers
        List numbers = new List();

        // Use DefaultIfEmpty with a default value of 0
        IEnumerable result = numbers.DefaultIfEmpty(0);

        Console.WriteLine("Result after DefaultIfEmpty:");
        foreach (int number in result)
        {
            Console.WriteLine(number); // This will output: 0
        }

        // Example with a sequence of strings
        List names = new List();
        IEnumerable defaultNames = names.DefaultIfEmpty("No Names");

        Console.WriteLine("\nResult for strings:");
        foreach (string name in defaultNames)
        {
            Console.WriteLine(name); // This will output: No Names
        }
    }
}
                

Example 2: Using DefaultIfEmpty with a non-empty sequence

The following code example demonstrates how to use the DefaultIfEmpty method on a non-empty sequence.


using System;
using System.Collections.Generic;
using System.Linq;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a non-empty list of integers
        List numbers = new List { 1, 2, 3 };

        // Use DefaultIfEmpty with a default value of 0
        // Since the sequence is not empty, the default value is ignored
        IEnumerable result = numbers.DefaultIfEmpty(0);

        Console.WriteLine("Result after DefaultIfEmpty:");
        foreach (int number in result)
        {
            Console.WriteLine(number); // This will output: 1, 2, 3
        }
    }
}