Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalents in C Sharp of Java's NavigableMap.floorEntry, ceilingEntry

I have used the NavigableMap interface many a time in Java, it's handy.

Specifically, I like to use its floorEntry and ceilingEntry methods, which get you the next lowest or highest map entry, respectively.

I am trying to find the equivalents of these in C# but I am coming up short. Below is an example of what I am trying to get.

I've looked at C# SortedDictionary and extension methods, and, while it seems like it'd be in the ballpark, I haven't found exactly what I'm looking for.

Thanks! L

package com.lewis.needsanavigablemapincsharp;

import java.util.NavigableMap;
import java.util.TreeMap;

public class Main {

    public static void main(String[] args) {

        NavigableMap<Float, String> neededMap = new TreeMap<Float, String>();

        neededMap.put(1.0f, "first!");
        neededMap.put(3.0f, "second!");

        System.out.println("see how useful this is? (looking up indices that aren't in my map)");
        System.out.println(neededMap.floorEntry(2.0f));
        System.out.println(neededMap.ceilingEntry(2.0f));

    }
}

the output is:

see how useful this is? (looking up indices that aren't in my map)
1.0=first!
3.0=second!

like image 447
lewiSnort Avatar asked Aug 14 '14 03:08

lewiSnort


1 Answers

The solution, unfortunately, requires you to write custom extensions. So, I have already done it, and uploaded it as a gist: SortedDictionaryExtensions.cs.

It makes use of the List<T>.BinarySearch method by converting the dictionary's key collection to a list. Then, with help to the answer here, we determine if the key exists, and if not, we get the floor and ceiling values as a bitwise complement, and then choose which one we need for the method.

Please note I haven't tested the efficiency of this algorithm, but as a first glance it seems good enough.

You can test it like this:

SortedDictionary<float, string> neededMap = new SortedDictionary<float, string>();

neededMap.Add(1.0f, "first!");
neededMap.Add(3.0f, "second!");

Console.WriteLine("see how useful this is? (looking up indices that aren't in my map)");
Console.WriteLine(neededMap.FloorEntry(2.0f));
Console.WriteLine(neededMap.CeilingEntry(2.0f));
like image 134
Arturo Torres Sánchez Avatar answered Oct 17 '22 00:10

Arturo Torres Sánchez