Hooked on LINQ

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

Quick Search

Advanced Search »

FirstOrDefault Operator

Modified: 2007/01/13 02:58 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 FirstOrDefault operator returns the first element of a sequence, or a default value if no element is found.

Edit

Method Signatures

// 1 - Return the first element of a sequence or default(TSource); if empty.
public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source)
 
// 2 - Return the first element that passes a predicate function in the sequence.
// Return default(TSource) if the sequence is empty.
public static TSource FirstOrDefault<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate)



Edit

Exceptions

Throws an ArgumentNullException if source or predicate is null.


Edit

Pseudo-code

Overload 1
If source is null, throw an ArgumentNullException.
If the source sequence implements IList<T>, then
If the source sequence is empty return default(TSource);.
Return source[0]. (performance optomization)
Else Iterate the source sequence.
If there is no first element, return default(TSource);.
Return the first (current element) element.

Overload 2
If source is null, throw an ArgumentNullException.
Iterate the source sequence.
If predicate(current element) returns true, return the current element.
Return default(TSource); if no elements pass the predicate function.


Edit

Loop Count

Overload 1
< 1. If the collection is of type IList, then the first element is accessed by index position which is different depending on the collection implementation. Otherwise, an iterator returns the first element.


Overload 2
< 1. The source sequence is iterated, and the first matching element is returned.

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.