IsOrderedBy Extension Method
c#, generics
Solution
I think it would make more sense to use a method signature similar to the `OrderBy` method...
public static bool IsOrderedBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
bool isFirstPass = true;
TSource previous = default(TSource);
foreach (TSource item in source)
{
if (!isFirstPass)
{
TKey key = keySelector(item);
TKey previousKey = keySelector(previous);
if (Comparer<TKey>.Default.Compare(previousKey, key) > 0)
return false;
}
isFirstPass = false;
previous = item;
}
return true;
}
You can then use it like that :
List<Foo> list = new List<Foo>();
...
if (list.IsOrderedBy(f => f.Name))
Console.WriteLine("The list is sorted by name");
else
Console.WriteLine("The list is not sorted by name");
Problem
In some of my tests i need to check the order of Lists and do it something like this ``` DateTime lastDate = new DateTime(2009, 10, 1); foreach (DueAssigmentViewModel assignment in _dueAssigments) { if (assignment.DueDate < lastDate) { Assert.Fail("Not Correctly Ordered"); } lastDate = assignment.DueDate; } ``` What i would like to do i turn this into an extension method on IEnumerable to make it reusable. My inital idea was this ``` public static bool IsOrderedBy<T, TestType>(this IEnumerable<T> value, TestType initalValue) { TestType lastValue = initalValue; foreach (T enumerable in value) { if(enumerable < lastValue) { return false; } lastValue = value; } return true; } ``` The ovious problem here is you cant compaire to generic values. Can anyone suggest a way round this. Cheers Colin