gpt4 book ai didi

java - Java 的 NavigableMap.floorEntry、ceilingEntry 的 C Sharp 等价物

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:40 29 4
gpt4 key购买 nike

我在 Java 中多次使用 NavigableMap 接口(interface),它很方便。

具体来说,我喜欢使用它的 floorEntryceilingEntry 方法,它们分别为您提供下一个最低或最高的 map 条目。

我试图在 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 ,我们确定 key 是否存在,如果不存在,我们得到下限值和上限值作为按位补码,然后选择我们需要的方法。

请注意,我还没有测试过该算法的效率,但乍一看似乎已经足够好了。

你可以这样测试:

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

关于java - Java 的 NavigableMap.floorEntry、ceilingEntry 的 C Sharp 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25299386/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com