[LINQ Operators] DefaultIfEmpty

The “DefaultIfEmpty” operator supplies a default element for an empty sequence. You can specify the default value, or “default(T)” is used.

 

1. Sample Data Object

To test examples, you need to include the <data classes> in your project.

 

2. “DefaultIfEmpty” operator

  • Deferred operator
  • Purpose: Elememt

 

3. Prototypes

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

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

The “DefaultIfEmpty()” operator returns a single element sequence if the output sequence is empty. The single element will be “default(T)” or the specified value. If the source sequence is not empty, it returns the source sequence itself.

 

4. Example 1 (Standard Operator)

var emps = Employee.GetEmployees();

var newEmps
  = emps.Where(e => e.CityId == 3).DefaultIfEmpty();
foreach (var e in newEmps)
{
  if (e != null)
  {
    Console.WriteLine($"{e.Name}");
  }
  else
  {
    Console.WriteLine("No employee lives in City whose Id is 3");
  }
}

 

5. Example 2 (Query Expression)

There’s no corresponding query expression for the “DefaultIfEmpty()” operator.

 

6. Example 3 (Standard Operator) – with a default value

int[] nums = {1, 2, 3, 4, 5};

var intNumbers
  = nums.Where(i => i > 10).DefaultIfEmpty();
foreach (var num in intNumbers)
{
  Console.WriteLine($"{num}"); // 0
}

var intNumbers1
  = nums.Where(i => i > 10).DefaultIfEmpty(-1);
foreach (var num in intNumbers1)
{
  Console.WriteLine($"{num}"); // -1
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s