Finding Consecutive Items in List using Linq

后端 未结 4 1420
借酒劲吻你
借酒劲吻你 2020-12-18 04:44

Say I have the following array of integers:

int[] numbers = { 1, 6, 4, 10, 9, 12, 15, 17, 8, 3, 20, 21, 2, 23, 25, 27, 5, 67,33, 13, 8, 12, 41, 5 };
<         


        
4条回答
  •  北海茫月
    2020-12-18 05:38

    I had to do this for a list of doubles. There is an upper as well as a lower limit. This is also not a true Linq solution, it is just a pragmatic approach I wrote this in scripting language that only implements a subset of C#.

    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();
    
            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();
            consec = 0;
    
            index = index+1;
    }
    
    return windows;
    

提交回复
热议问题