ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsSingle

Determines whether the collection has exactly one element

Source

/// <summary>
/// Determines whether a sequence contains exactly one element.
/// </summary>
/// <typeparam name="T">The type of the elements of <paramref name="source"/></typeparam>
/// <param name="source">The <see cref="IEnumerable{T}"/> to check for singularity.</param>
/// <returns>
/// <c>true</c> if the <paramref name="source"/> sequence contains exactly one element; otherwise, <c>false</c>.
/// </returns>
public static bool IsSingle<T>(this IEnumerable<T> source)
{
    if (source == null) 
    {
        throw new ArgumentNullException("source");
    }

    using (var enumerator = source.GetEnumerator())
    {
        return enumerator.MoveNext() && !enumerator.MoveNext();
    }
}

Example

var items = new[] { 1, 2, 3 };
items.IsSingle(); // returns false
items.Take(1).IsSingle(); // returns true
new List<object>().IsSingle(); // returns false

Author: Brian Dukes

Submitted on: 21 okt. 2010

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5685