Method AssertCount
| Edit this pageAssertCount<TSource>(IEnumerable<TSource>, int)
Asserts that a source sequence contains a given count of elements.
Declaration
public static IEnumerable<TSource> AssertCount<TSource>(this IEnumerable<TSource> source, int count)
Parameters
| Type | Name | Description |
|---|---|---|
| IEnumerable<TSource> | source | Source sequence. |
| int | count | Count to assert. |
Returns
| Type | Description |
|---|---|
| IEnumerable<TSource> | Returns the original sequence as long it is contains the number of elements specified by |
Type Parameters
| Name | Description |
|---|---|
| TSource | Type of elements in |
Remarks
This operator uses deferred execution and streams its results.
The sequence length is evaluated lazily during the enumeration of the sequence.
Examples
The following code example demonstrates how to validate the length of a sequence using AssertCount.
var numbers = new string[] { "1", "2", "3", "4", "5", };
// Enumerate the sequence with a valid length.
// This code executes normally.
numbers
.AssertCount(5)
.Consume();
// Enumerate the sequence with an invalid length.
// This code throws an `ArgumentException`
try
{
numbers
.AssertCount(4)
.Consume();
}
catch (ArgumentException ae)
{
Console.WriteLine(ae.Message);
// This code produces the following output:
// Parameter "source.Count()" (int) must be equal to <4>, was <5>. (Parameter 'source.Count()')
}
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException |
|
| ArgumentOutOfRangeException |
|
| InvalidOperationException | Thrown lazily |