Linq By Example

DefaultIfEmpty

Default If Empty allows you to retrieve the value of a list or if the list is empty, a default value from the list. The default value is determined by the (default)T value.

DefaultIfEmpty With Value Types

As an example, the following code outputs the value "0" because the list is empty, and the default value for an integer is 0.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List<int>();
foreach(var item in myList.DefaultIfEmpty())
{
    Console.WriteLine(item);
}

  

DefaultIfEmpty With Reference Types

In the following code, because we are utilizing reference types (As a simple object type), then the default value will instead be null.
    
using System;
using System.Collections.Generic;
using System.Linq;

var objectList = new List<object>();
foreach(var item in objectList.DefaultIfEmpty())
{
    if(item == null)
    {
        Console.WriteLine("Item is null!");
    } else
    {
        Console.WriteLine("Item is not null!");
    }
}

  

Passing A Default Value To DefaultIfEmpty

If the default value is not useful to you, you can instead pass in a value that you want to use as the default. Below, the value of -1 is output instead of 0.
    
using System;
using System.Collections.Generic;
using System.Linq;

var myList = new List<int>();
foreach(var item in myList.DefaultIfEmpty(-1))
{
    Console.WriteLine(item);
}