C#: Finding consecutive list items violating an upper or lower limit

Here’s some code I have written today to find segments of a list that violate upper or lower limits. The minimum size is given as a parameter.

I know there are more elegant ways to do this, but the scripting language that I used features only a subset of C#, that is why I had to keep it simple, e.g. without Predicate.

var sequence = [0.25,0.5,0.5,0.5,0.7,0.8,0.7,0.9,0.5,0.5,0.8,0.8,0.5,0.5,0.65,0.65,0.65,0.65,0.65,0.65,0.65];
double lowerLimit = 0.1;
double upperLimit = 0.6;
int minWindowLength = 3;

// return type is a list of lists
var windows = [[0.0]];
windows.Clear();

int consec = 0;
int index = 0;

while (index < sequence.Count){

// store segments here
var window = new System.Collections.Generic.List<double>();

while ((index < sequence.Count) && (sequence[index] > upperLimit || sequence[index] < lowerLimit)) {
window.Add(sequence[index]);
consec = consec + 1;
index = index +1;
}

if (consec > minWindowLength) {
windows.Add(window);
}

window = new System.Collections.Generic.List<double>();
consec = 0;

index = index+1;
}

return windows;

Leave a Reply

Your email address will not be published. Required fields are marked *