Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Quick Search

Advanced Search »

DefaultIfEmpty Operator

Modified: 2007/01/12 19:55 by t_magennis - Categorized as: LINQ to Objects
{TOC}
Namespace:System.Linq
Assembly:System.Core.dll
Extends:IEnumerable<T>

Back to Standard Query Operator Index


Edit

Introduction

The DefaultIfEmpty operator supplies a default element for an empty sequence. One use of this operator is when performing outer joins on two sequences as in the Outer Join Sample.

Edit

Method Signatures

// 1 - Returns the source sequence, or the default(TSource) if the source sequence has no elements
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
    this IEnumerable<TSource> source)
 
// 2 - Returns the source sequence, or the defaultValue specified if the source sequence has no elements.
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(
    this IEnumerable<TSource> source, 
    TSource defaultValue)



Edit

Exceptions

Throws an ArgumentNullException if source is null

Edit

Pseudo-code

Overload 1
If source is null, throw an ArgumentNullException.
If there are no elements in the source sequence, return the result of default(TSource);
Iterate the source sequence.
Return the current element (pick up from here when the next element is requested).

Overload 2
If source is null, throw an ArgumentNullException.
If there are no elements in the source sequence, return defaultValue.
Iterate the source sequence.
Return the current element (pick up from here when the next element is requested).

Edit

Loop Count

This operator implements the standard deferred execution iterator pattern. This means, no looping will occur until the result is iterated over.. If there are no elements in the source sequence, one single element is returned using the iterator pattern.

Edit

Code Samples

TODO:Needs code sample.

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or ommissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain un-intentional errors - please use care. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.