C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument: You can pass an argument to DefaultIfEmpty. This will become the value that is used in the singleton collection's value.
C# program that uses DefaultIfEmpty
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Empty list.
List<int> list = new List<int>();
var result = list.DefaultIfEmpty();
// One element in collection with default(int) value.
foreach (var value in result)
{
Console.WriteLine(value);
}
result = list.DefaultIfEmpty(-1);
// One element in collection with -1 value.
foreach (var value in result)
{
Console.WriteLine(value);
}
}
}
Output
0
-1
Tip: You could pass a reference to the null object to DefaultIfEmpty. Then methods can act without knowing about empty collections.