The DefaultIfEmpty() method in LINQ is used to return a default value when a collection is empty.
If the collection has elements, it remains unchanged.
If the collection is empty, it returns a collection with a single default value (for example,
0 for numbers, and null for reference types).
Basic Use
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int>(); // Empty list
var result = numbers.DefaultIfEmpty(); // Returns a collection with one element: 0
Console.WriteLine("Result: " + string.Join(", ", result));
// Output: Result: 0 (default int value)
}
}
DefaultIfEmpty() with Linq to SQL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyConsoleApplication
{
class MindStickSoft
{
static void Main()
{
List<int> Numbers = new List<int> { 3, 5, 7, 2, 8, 4 };
var filterValue = Numbers.Where(x => x > 20).DefaultIfEmpty(-1); // now value exist greater than 20;
Console.WriteLine("Dafult value is: {0}", string.Join(',', filterValue));
// Output: Dafult value is: -1
}
}
}
When to it
When working with queries that may return empty collections but require at least one value.
When aggregation functions (sum, average, etc.) are used to avoid exceptions on empty collections.
When a fallback/default value is provided instead of manually handling empty collections.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
DefaultIfEmpty() in LINQ (C#)
DefaultIfEmpty()method in LINQ is used to return a default value when a collection is empty.0for numbers, andnullfor reference types).Basic Use
DefaultIfEmpty() with Linq to SQL
When to it
Also, read: What are the LINQ Single(), and SingleOrDefault() functions?