Hooked on LINQ

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

Quick Search

Advanced Search »

Single Operator

Modified: 2007/01/21 18:50 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 Single operator returns the single element of a sequence.

Edit

Method Signatures

// 1 - Get the first and only record
public static TSource Single<TSource>(
    this IEnumerable<TSource> source)
 
// 2 - Gets the only record that passes the predicate function
public static TSource Single<TSource>(
    this IEnumerable<TSource> source, 
    Func<TSource, bool> predicate)



Edit

Exceptions

Throws an ArgumentNullException if source or predicate is null.
Throws an InvalidOperationException if source is empty.
Throws an InvalidOperationException if no records, or more than one record pass the predicate function.


Edit

Pseudo-code

Overload 1
If source is null, throw an ArgumentNullException.
If source is of type IList.
If there are no elements in source, throw an InvalidOperationException.
If there is more than one element in source, throw an InvalidOperationException.
Return source[0], the first and only element by index position. (performance enhancement).
Else
Iterate over source
If there is no first record in source, throw an InvalidOperationException.
If there is more than one element in source, throw an InvalidOperationException.
Return the current-element (we only ever iterate to the first record).

Overload 2
If source is null, throw an ArgumentNullException.
If predicate is null, throw an ArgumentNullException.
Initialize a counter to zero.
Iterate the source sequence.
If predicate(current element) returns true.
Remember the current element.
Increment the counter by 1.
If counter is zero, throw an InvalidOperationException.
If counter > 1 (more than one element passed the predicate function), throw an InvalidOperationException.
Return the one and only element that passed the predicate.


Edit

Loop Count

Overload 1
< 1. If source is an IList type, the first element is accessed by index which is very quick, otherwise the first (and second if it exists) is enumerated.


Overload 2
1. Source is iterated once to find a matching element or to ascertain if there is more than one element that passes the predicate function.


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.