English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

LINQ Generate Operator DefaultIfEmpty

If the given collection to DefaultIfEmpty() is empty, the DefaultIfEmpty() method will return a new collection with the default value.

Another overloaded method of DefaultIfEmpty() accepts a value parameter that should be used as the default value.

See the following example.

IList<string> emptyList = new List<string>();
var newList1 = emptyList.DefaultIfEmpty(); 
var newList2 = emptyList.DefaultIfEmpty("None"); 
Console.WriteLine("Count: {0}", newList1.Count());
Console.WriteLine("Value: {0}", newList1.ElementAt(0));
Console.WriteLine("Count: {0}", newList2.Count());
Console.WriteLine("Value: {0}", newList2.ElementAt(0));
Output:

Count: 1
Value:
Count: 1
Value: None

In the above example, emptyList.DefaultIfEmpty() returns a new string collection with a null value for one of its elements, as null is the default value for string. Another method, emptyList.DefaultIfEmpty("None"), returns a string collection with one of its elements set to "None" instead of null.

This example demonstrates how to call DefaultIfEmpty on an int collection.

IList<int> emptyList = new List<int>();
var newList1 = emptyList.DefaultIfEmpty(); 
var newList2 = emptyList.DefaultIfEmpty(100);
Console.WriteLine("Count: {0}", newList1.Count());
Console.WriteLine("Value: {0}", newList1.ElementAt(0));
Console.WriteLine("Count: {0}", newList2.Count());
Console.WriteLine("Value: {0}", newList2.ElementAt(0));
Output:

Count: 1
Value: 0
Count: 1
Value: 100

The following example demonstrates the DefaultIfEmpty() method for complex type collections.

IList<Student> emptyStudentList = new List<Student>();
var newStudentList1 = studentList.DefaultIfEmpty(new Student());
                 
var newStudentList2 = studentList.DefaultIfEmpty(new Student() { 
                StudentID = 0, 
                StudentName = ""});
Console.WriteLine("Count: {0}", newStudentList1.Count());
Console.WriteLine("Student ID: {0}", newStudentList1.ElementAt(0));
Console.WriteLine("Count: {0}", newStudentList2.Count());
Console.WriteLine("Student ID: {0}", newStudentList2).ElementAt(0).StudentID);
Output:

Count: 1
Student ID:
Count: 1
Student ID: 0