I want to write a lambda expression to verify that a list is ordered correctly. I have a List where a person has a Name property eg:
IList<Person> people = new List<Person>();
people.Add(new Person(){ Name = "Alan"});
people.Add(new Person(){ Name = "Bob"});
people.Add(new Person(){ Name = "Chris"});
I'm trying to test that the list is ordered ASC by the Name property.So I'm after something like
Assert.That(people.All(....), "list of person not ordered correctly");
How can I write a lambda to check that each Person in the list has a name less that the next person in the list?
Here's an alternative to Jared's solution - it's pretty much the same, but using a foreach loop and a Boolean variable to check whether or not this is the first iteration. I usually find that easier than iterating manually:
public static bool IsOrdered<T>(this IEnumerable<T> source)
{
var comparer = Comparer<T>.Default;
T previous = default(T);
bool first = true;
foreach (T element in source)
{
if (!first && comparer.Compare(previous, element) > 0)
{
return false;
}
first = false;
previous = element;
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With