【问题标题】:How can I check if a sequence of values is correctly ordered?如何检查值序列是否正确排序?
【发布时间】:2011-02-07 14:45:05
【问题描述】:

我有很多 Action 对象,其属性为 long Timestamp。我想做这样的事情:

Assert.IsTrue(a1.Timestamp < a2.Timestamp < a3.Timestamp < ... < an.Timestamp);

很遗憾,这种语法是非法的。是否有内置方式或扩展\LINQ\whatever 方式来执行此操作?

请注意,它是单元测试类的目标,所以要发疯。我不关心性能、可读性等。

【问题讨论】:

    标签: c# .net comparison syntactic-sugar


    【解决方案1】:
    private static bool isValid(params Action[] actions)
    {
      for (int i = 1; i < actions.Length; i++)
        if (actions[i-1].TimeStamp >= actions[i].TimeStamp)
          return false;
      return true;
    }
    
    Assert.IsTrue(isValid(a1,a2,...,an));
    

    【讨论】:

    • 我选择这个是因为它可以让我通过将 return false; 更改为 return i; 来知道哪里出了问题
    【解决方案2】:

    怎么样:

    Action[] actions = { a1, a2, a3, ... an };
    Assert.IsTrue
      (actions.Skip(1)
              .Zip(action, (next, prev) => prev.Timestamp < next.Timestamp)
              .All(b => b));
    

    【讨论】:

      【解决方案3】:
      public bool InOrder(params long[] data)
      {
        bool output = true;
      
        for (int i = 0; i <= data.Count-1;i++)
        {
          output &= data[i] < data[i + 1];
        }
        return output;
      }
      

      我使用了 for 循环,因为这可以保证迭代的顺序,而 foreach 循环不会这样做。

      【讨论】:

        【解决方案4】:

        假设actions 是一个列表或数组:

        actions.Skip(1).Where((x,index)=>x.Timespan > actions[i].Timespan).All(x=>x)
        

        【讨论】:

        • 我刚刚写了一个类似的,但使用三元运算符而不是跳过。跳过要好得多。顺便说一句,我认为Count() == 0 比 `.All(x=>x)' 更好。
        • @HuBeZa,是的,您可以使用 Count() = 0,我不知道 Count() 的确切运行时间(可能是 n)如果是这样的话,一切都更好,因为这个我没有写 Count() :)
        猜你喜欢
        • 2012-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-05
        • 2011-06-10
        • 1970-01-01
        • 2011-07-06
        • 1970-01-01
        相关资源
        最近更新 更多