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

CountOf

Returns whether the sequence contains a certain amount of elements, without having to traverse the entire collection.

Source

/// <summary>
///   Returns whether the sequence contains a certain amount of elements.
/// </summary>
/// <typeparam name = "T">The type of the elements of the input sequence.</typeparam>
/// <param name = "source">The source for this extension method.</param>
/// <param name = "count">The amount of elements the sequence should contain.</param>
/// <returns>True when the sequence contains the specified amount of elements, false otherwise.</returns>
public static bool CountOf<T>( this IEnumerable<T> source, int count )
{
	Contract.Requires( source != null );
	Contract.Requires( count >= 0 );

	return source.Take( count + 1 ).Count() == count;
}

Example

int[] bigCollection = new[] { 0, 1, 2, 3, 4, .... int.MaxValue };
bool hasTen = bigCollection.CountOf( 10 ); // true

Author: Steven Jeuris

Submitted on: 15 nov. 2011

Language: C#

Type: System.IEnumerable<T>

Views: 5360