HuBeZa
HuBeZa

Reputation: 4761

How can I check if a sequence of values is correctly ordered?

I have many Action objects with a property long Timestamp. I want to do something like this:

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

Unfortunately, this syntax is illegal. Is there a built-in way or a extension\LINQ\whatever way to perform this?

Note that it's target for a unit test class, so get crazy. I don't care about performance, readability and etc.

Upvotes: 4

Views: 193

Answers (4)

Saeed Amiri
Saeed Amiri

Reputation: 22555

by assuming actions is a List or array:

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

Upvotes: 1

Ani
Ani

Reputation: 113402

How about:

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

Upvotes: 4

Itay Karo
Itay Karo

Reputation: 18286

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

Upvotes: 6

Femaref
Femaref

Reputation: 61437

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

I used a for loop as this guarantees the order of the iteration, what a foreach loop wouldn't do.

Upvotes: 1

Related Questions