How to find point between two keys in sorted dictionary

后端 未结 5 1138
生来不讨喜
生来不讨喜 2021-01-22 23:43

I have a sorted dictionary that contains measured data points as key/value pairs. To determine the value for a non-measured data point I want to extrapolate the value between t

5条回答
  •  情歌与酒
    2021-01-23 00:14

    regular loop should be ok here:

    IEnumerable keys = ...; //ordered sequence of keys
    double interpolatedKey = ...;
    
    // I'm considering here that keys collection doesn't contain interpolatedKey
    
    double? lowerFoundKey = null;
    double? upperFoundKey = null;
    
    foreach (double key in keys)
    {
        if (key > interpolatedKey)
        {
            upperFoundKey = key;
            break;
        }
        else
            lowerFoundKey = key;
    }
    

    You can do it in C# with LINQ with shorter but less effective code:

    double lowerFoundKey = key.LastOrDefault(k => k < interpolatedKey);
    double upperFoundKey = key.FirstOrDefault(k => k > interpolatedKey);
    

    In order to it efficiently with LINQ it should have a method which is called windowed in F# with parameter 2. It will return an IEnumerable of adjacent pairs in keys collection. While this function is missing in LINQ regular foreach loop should be ok.

提交回复
热议问题