CollectionOrdered Constraint
CollectionOrderedConstraint tests that an IEnumerable is ordered. An exception is thrown if the actual value does
not implement IEnumerable.
Usage
Is.Ordered
Is.Ordered.Ascending
Is.Ordered.Descending
Is.Ordered.By(string propertyName)
Modifiers
.Ascending // Ascending order (default)
.Descending // Descending order
.By(string propertyName) // Order by property
.Then // Begin next ordering step
.Using(IComparer comparer)
.Using<T>(IComparer<T> comparer)
.Using<T>(Comparison<T> comparer)
Examples
Simple Ordering
[Test]
public void CollectionOrderedConstraint_Examples()
{
int[] ascending = { 1, 2, 3, 4, 5 };
int[] descending = { 5, 4, 3, 2, 1 };
string[] alphabetical = { "Alice", "Bob", "Carol" };
// Simple ordering
Assert.That(ascending, Is.Ordered); // Default is ascending
Assert.That(ascending, Is.Ordered.Ascending); // Explicit ascending
Assert.That(descending, Is.Ordered.Descending); // Descending order
Assert.That(alphabetical, Is.Ordered); // Alphabetical order
// Property-based ordering
string[] byLength = { "a", "bb", "ccc" };
Assert.That(byLength, Is.Ordered.By("Length"));
Assert.That(byLength.Reverse(), Is.Ordered.Descending.By("Length"));
// Custom comparison
var words = new[] { "apple", "Banana", "cherry" };
Assert.That(words, Is.Ordered.Using((IComparer<string>)StringComparer.OrdinalIgnoreCase));
}
Multiple Property Ordering
[Test]
public void CollectionOrdered_MultipleProperties_Examples()
{
var people = new[]
{
new { Name = "Alice", Age = 25 },
new { Name = "Bob", Age = 25 },
new { Name = "Carol", Age = 30 }
};
// Order by Age ascending, then by Name ascending
Assert.That(people, Is.Ordered.By("Age").Then.By("Name"));
}
Notes
- The default ordering is ascending.
- The
Thenmodifier separates ordering steps. Each step can have its ownAscending/DescendingandUsingmodifiers. - An empty or single-item collection is always considered ordered.
See Also
- CollectionEquivalent Constraint - Test equivalence regardless of order
- UniqueItems Constraint - Test for unique items