IsOrderedBy扩展方法 [英] IsOrderedBy Extension Method

查看:175
本文介绍了IsOrderedBy扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一些测试中,我需要检查列表的顺序,做这样的事情。

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



我想这样做我把它变成一个扩展方法对IEnumerable的到使其可重复使用的。

What i would like to do i turn this into an extension method on IEnumerable to make it reusable.

我inital的想法是这样的。

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



这里的ovious问题是你不能compaire仿制值。任何人都可以提出一个解决方法这一点。

The ovious problem here is you cant compaire to generic values. Can anyone suggest a way round this.

干杯
科林

推荐答案

我相信这会令使用类似排序依据方法...

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

您可以使用它这样的:

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");

这篇关于IsOrderedBy扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆