c# - IsOrderedBy 扩展方法

标签 c# generics

在我的一些测试中,我需要检查列表的顺序并执行类似这样的操作

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 上的扩展方法,使其可重用。

我最初的想法是这样的

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

这里的一个明显问题是您无法与通用值进行比较。谁能提出解决这个问题的方法。

干杯 科林

最佳答案

我认为使用类似于 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;
}

然后你可以像这样使用它:

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

关于c# - IsOrderedBy 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1082624/

相关文章:

swift - 如何在方法签名中使用泛型协议(protocol)?

c# - 如何在词典集中查找项目?

TypeScript:获取 keyof T 处的属性类型

java - 泛型 java 中的逆变不能按预期工作

c# - 使用 MySQL 查询填充列表<string>

c# - windows mobile 6.5 wceload.exe - 如何设置目标安装目录?

c# - ConcurrentDictionary.GetOrAdd() 是否保证每个键只调用一次 valueFactoryMethod?

c# - 无法使用打开的 xml 在 word 中找到合并字段

c# - 在 List<Parent> 对象的泛型函数中使用子类型

c# - 如何开始使用 C# 4.0 和 .NET 4.0?