Search code examples
c#sorteddictionary

How to find point between two keys in sorted dictionary


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 two known keys using a linear interpolation of their corresponding values. I understand how to calculate the non-measured data point once I have the two key/value pairs it lies between. What I don't know is how to find out which keys it lies between. Is there a more elegant way than a "for" loop (I'm thinking function/LINQ query) to figure out which two keys my data point lies between?


Solution

  • 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.