Matze-Berlin
Matze-Berlin

Reputation: 197

checking a sequence for proper order in c#

I am looking for a way to "detect" if a sequence of ordered objects turns out of order.

I try to explain it with an simplified example:

I am using an IEnumerable of TourStop which is defined as this:

class TourStop 
{
    public int Id {get;set;}
    public int Sorting {get;set;}
    public string LocationTitle {get;set;}
    public bool Done {get;set;}
}

As my piece of software is used by humans, it's possible that a user set the done property in a random order which would lead to gaps in the "processing order". And that's what I want to extract from the collection: "Give me all TourStops which are not done and seem to be out of order".

And now the tricky part! Here are some examples as a simple boolean array:

[1,1,1,0,0,0] // the algorithm should return nothing. The first three elements are processed in correct order and the rest of them may not be processed yet
[0,1,1,0,0,0] // here the algorithm should return only the first element
[1,0,0,1,1,0] // here the algorithm should return only the 2nd and 3rd element

Any ideas how to build such a query?

Upvotes: 0

Views: 979

Answers (1)

Roman
Roman

Reputation: 12171

Assume you have List of TourStop. So, you need to find all "0" before last "1":

List<TourStop> tourStops = new List<TourStop>();

// initialize list with your values

int index = tourStops.FindLastIndex((t) => t.Done);

List<TourStop> outOfOrder = null;

if (index > 0)
{
    outOfOrder = tourStops.Where((el) => !el.Done && tourStops.LastIndexOf(el) < index).ToList();
}

After that you can check if outOfOrder == null.

If so, there are not out of order elements.

If not, outOfOrder will contain all out of order elements.

Also, you can try query which @juharr commented.

Upvotes: 1

Related Questions