简体   繁体   中英

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!

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM