Search code examples
c#keyvaluepairsorteddictionary

How to get Key of Value that is greater than three Values above and below


I've got a sortedDict = new SortedDictionary<double,double>();

And I'm trying to get the Key of the Value that is greater than the three Values above and three Values below but I don't know how.

sortedDict looks like this:

{
1.10 , 20
1.09 , 75
1.08 , 32
1.07 , 440 ------> This Value is greater than the Values of 3 keys above and below
1.06 , 200
1.05 , 160
1.04 , 130
1.03 , 250 ------> This Value is greater than the Values of 3 keys above and below
1.02 , 62
1.01 , 73
1.00 , 15
}

Output: (How do I get this?)
 1.07
 1.03

Any help will be greatly appreciated.


Solution

  • I deleted my earlier answer to post this. It's working code to do what you're asking

       static void Main(string[] args)
        {
            var sortedDict = new SortedDictionary<double, double>()
            { {
                1.10 , 20 },{
                1.09 , 75 },{
                1.08 , 32 },{
                1.07 , 440},{
                1.06 , 200},{
                1.05 , 160},{
                1.04 , 130},{
                1.03 , 250},{
                1.02 , 62 },{
                1.01 , 73 },{
                1.00 , 15 }
            };
    
            var totalLen = sortedDict.Count;
            for(var i = 0; i < sortedDict.Count; i++)
            {
                var val = sortedDict.ElementAt(i);
    
                if (i - 3 >= 0 && i + 3 < totalLen)
                {
                    if (
                        sortedDict.ElementAt(i - 3).Value < val.Value &&
                        sortedDict.ElementAt(i - 2).Value < val.Value &&
                        sortedDict.ElementAt(i - 1).Value < val.Value &&
                        sortedDict.ElementAt(i + 1).Value < val.Value &&
                        sortedDict.ElementAt(i + 2).Value < val.Value &&
                        sortedDict.ElementAt(i + 3).Value < val.Value
                     )
                    {
                        Console.WriteLine(val.Key);
                    }
                }
            }
        }