---
title: "How to use DefaultIfEmpty() function in LINQ with C#?"  
description: "How to use DefaultIfEmpty() function in LINQ with C#?"  
author: "Ashutosh Patel"  
published: 2025-02-12  
updated: 2025-02-13  
canonical: https://www.mindstick.com/forum/161158/how-to-use-defaultifempty-function-in-linq-with-c-sharp  
category: "linq"  
tags: ["linq", "linq function"]  
reading_time: 2 minutes  

---

# How to use DefaultIfEmpty() function in LINQ with C#?

How to use the DefaultIfEmpty() [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) in LINQ with C#?

## Replies

### Reply by Amrith Chandran

#### DefaultIfEmpty() in LINQ (C#)

- 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

```cs
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

```cs
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.

**Also, read:** [What are the LINQ Single(), and SingleOrDefault() functions?](https://www.mindstick.com/forum/161157/what-are-the-linq-single-and-singleordefault-functions)


---

Original Source: https://www.mindstick.com/forum/161158/how-to-use-defaultifempty-function-in-linq-with-c-sharp

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
