CountOf

/// <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

Description

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

Details

Double click on the code to select all.

 

;