I’m unit testing a UI that needs to show some lists in various sorted orders, and I wanted to ensure that my tests would cover that. I found this method to come in handy:

 

   1:  public static bool IsOrderedBy<T>(this IEnumerable<T> coll,
   2:                     Func<T, IComparable> val)
   3:  {
   4:      if (coll == null || coll.Count() == 0)
   5:          return true;
   6:   
   7:      var curVal = val(coll.ElementAt(0));
   8:      for (int i = 0; i < coll.Count(); i++)
   9:      {
  10:          if (val(coll.ElementAt(i)).CompareTo(curVal) < 0)
  11:              return false;
  12:   
  13:          curVal = val(coll.ElementAt(i));
  14:      }
  15:   
  16:      return true;
  17:  }

 

Here’s how to determine if a simple array is in order:

var arr = new int[] { 1, 2, 3, 5 };
bool ordered = arr.IsOrderedBy(i => i);

 

Here’s how you’d call it on a more complex object:

var arr = Enumerable.Range(1, 10)
    .Select(e => new
    {
        Name = "bob",
        Salary = 10 * e
    });
bool ordered = arr.IsOrderedBy(i => i.Salary);

 

 

Avi