Java的NavigableMap.floorEntry的C Sharp中的等价物,ceilingEntry

我在 Java中多次使用NavigableMap接口,这很方便.

具体来说,我喜欢使用它的floorEntry和ceilingEntry方法,它们分别为您提供下一个最低或最高的地图条目.

我试图在C#中找到它们的等价物,但我很简短.以下是我想要获得的一个例子.

我看过C#SortedDictionary和扩展方法,虽然它看起来像是在球场,但我还没找到我正在寻找的东西.

谢谢!
大号

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

    }
}

输出是:

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

解决方法

遗憾的是,该解决方案要求您编写自定义扩展.所以,我已经完成了它,并将其作为一个要点上传SortedDictionaryExtensions.cs.

它通过将字典的密钥集合转换为列表来利用List< T> .BinarySearch方法.然后,在答案here的帮助下,我们确定密钥是否存在,如果不存在,我们将楼层和天花板值作为按位补码,然后选择我们需要的方法.

请注意我没有测试过这种算法的效率,但乍一看似乎还不错.

你可以像这样测试它:

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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...