How to find point between two keys in sorted dictionary

后端 未结 5 1199
生来不讨喜
生来不讨喜 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:17

    Something like this would work:

     dic.Keys.Zip(dic.Keys.Skip(1), 
                  (a, b) => new { a, b })
             .Where(x => x.a <= datapoint && x.b >= datapoint)
             .FirstOrDefault();
    

    This traverses they keys using the fact that they are ordered and compares all two keys following each other in order - since LINQ is lazy once you find the first match the traversal will stop.

提交回复
热议问题