CSharp - LINQ DefaultIfEmpty

Introduction

DefaultIfEmpty operator returns a sequence containing a default element if the input source sequence is empty.

For reference and nullable types, the default value is null.

Prototypes

There are two prototypes for the DefaultIfEmpty operator we will cover.

public static IEnumerable<T> DefaultIfEmpty<T>(
  this IEnumerable<T> source);

The second prototype allows the default value to be specified.

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

This operator is useful if the input source sequence is empty.

This operator is useful in conjunction with the GroupJoin operator for producing left outer joins.

Exceptions

ArgumentNullException is thrown if the source argument is null.

The following code shows the example of the first DefaultIfEmpty prototype with an empty sequence.

In this example, we will not use the DefaultIfEmpty operator to see what happens.

Demo

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
class Program/*from  w  w w.  j av  a 2s . co  m*/
{
    static void Main(string[] args)
    {
        string[] codeNames = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};
        
        string jones = codeNames.Where(n => n.Equals("Jones")).DefaultIfEmpty().First();
        if (jones != null)
          Console.WriteLine("Jones was found.");
        else
          Console.WriteLine("Jones was not found.");
        
        
        jones = codeNames.Where(n => n.Equals("Jones")).First();
        if (jones != null)
                Console.WriteLine("Jones was found");
        else
                Console.WriteLine("Jones was not found");

    }
}

Result

Related Topics