Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda expression to verify list is correctly ordered

Tags:

c#

lambda

linq

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?

like image 546
Dav Evans Avatar asked Aug 26 '26 12:08

Dav Evans


1 Answers

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;
}
like image 127
Jon Skeet Avatar answered Aug 28 '26 01:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!