IsOrderedBy Extension Method

In some of my tests, I need to check the order of the lists and do 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 in IEnumerable to make it reusable.

My inner idea was that

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 obvious problem is that you cannot match common values. Can someone suggest a way around this.

Cheers Colin

+3
source share
3 answers

I think it would be wiser to use a method signature similar to a method OrderBy...

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;
}

Then you can use it like this:

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");
+5
source

You can add a restriction:

where T:IComparable

< CompareTo() IComparable.

+5

You should do something like this (I don't understand why it TestTypeshould be different from T):

public static bool IsOrderedBy<T>(this IEnumerable<T> value, T initalValue)
      where T : IComparable<T> {

      var currentValue = initialValue;

      foreach(var i in value) {
           if (i.CompareTo(currentValue) < 0)
                return false;
           currentValue = i;
      }

      return true;
}
+1
source

Source: https://habr.com/ru/post/1711858/


All Articles