DefaultIfEmpty

In this chapter you will learn:

  1. How to use DefaultIfEmpty operator
  2. Use DefaultIfEmpty after where clause

Get to know DefaultIfEmpty operator

Returns the elements of the specified sequence or just returns the type parameter's default value in a singleton collection if the sequence is empty.

using System;//from jav  a  2 s  .c o  m
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
   public static void Main() {
      List<int> numbers = new List<int>();

      foreach (int number in numbers.DefaultIfEmpty()){
         Console.WriteLine(number);
      }
   }
}

DefaultIfEmpty after where clause

using System;/*from   j  a v a2s.c o  m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"G", "H", "a", "H", "over", "Jack"};

        string jones = presidents.Where(n => n.Equals("H")).DefaultIfEmpty().First();
        if (jones != null)
            Console.WriteLine("H was found.");
        else
            Console.WriteLine("H was not found.");
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use Distinct operator
  2. Use Linq Distinct to get the distinct value in an array
  3. Distinct characters in an array
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip