DefaultIfEmpty
is a LINQ method that is used to return a default value if a sequence is empty, or the original sequence if it is not empty. It is defined in the System.Linq
namespace and is a member of the Enumerable
class.
The DefaultIfEmpty
method takes a single parameter of the same type as the elements in the sequence. This parameter specifies the default value to return if the input sequence is empty. If the input sequence is not empty, DefaultIfEmpty
returns the original sequence.
Here is the syntax for the DefaultIfEmpty
method:
1 2 3 |
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue); |
The DefaultIfEmpty
method returns an IEnumerable<TSource>
sequence that contains the default value if the input sequence is empty, or the original sequence if it is not empty.
Here is an example of how to use the DefaultIfEmpty
method:
1 2 3 4 5 6 7 |
int[] numbers = { 1, 2, 3 }; int[] result = numbers.DefaultIfEmpty(0).ToArray(); // result is { 1, 2, 3 } |
In this example, the input sequence is not empty, so DefaultIfEmpty
returns the same sequence.
1 2 3 4 5 6 7 |
int[] numbers = new int[0]; int[] result = numbers.DefaultIfEmpty(0).ToArray(); // result is { 0 } |
In this example, the input sequence is empty, so DefaultIfEmpty
returns a singleton sequence that contains the default value of 0.
Here is an example of a C# program that demonstrates the use of the DefaultIfEmpty
method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Linq; namespace DefaultIfEmptyExample { class Program { static void Main(string[] args) { // Create an empty integer array int[] emptyArray = new int[0]; // Use DefaultIfEmpty to return a default value if the array is empty int[] defaultArray = emptyArray.DefaultIfEmpty(0).ToArray(); // Output the default array Console.WriteLine("Default array: {0}", string.Join(", ", defaultArray)); // Create a non-empty integer array int[] nonEmptyArray = new int[] { 1, 2, 3 }; // Use DefaultIfEmpty to return a default value if the array is empty int[] sameArray = nonEmptyArray.DefaultIfEmpty(0).ToArray(); // Output the same array Console.WriteLine("Same array: {0}", string.Join(", ", sameArray)); } } } |
This program will output the following:
1 2 3 4 |
Default array: 0 Same array: 1, 2, 3 |
The DefaultIfEmpty
method returns a singleton sequence that contains the default value of the type if the input sequence is empty, or the input sequence if it is not empty. In this example, the default value for integers is 0. If the input array is empty, DefaultIfEmpty
returns a singleton sequence that contains the default value of 0. If the input array is not empty, DefaultIfEmpty
returns the same array.