Equivalents in C Sharp Java NavigableMap.floorEntry, ceilingEntry

I used the NavigableMap interface many times in Java, it is convenient.

In particular, I like to use the floorEntry and ceilingEntry , which you will get the next lowest or highest map entry, respectively.

I am trying to find equivalents of them in C #, but I do not understand. Below is an example of what I'm trying to get.

I looked at C # SortedDictionary and extension methods, and although it seems like it will be in a chalet, 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)); } } 

output:

See how useful this is? (search for indexes not on my map)
1,0 = first!
3.0 = second!

+6
source share
1 answer

The solution, unfortunately, requires you to write custom extensions. So, I already did this and uploaded it as an entity: SortedDictionaryExtensions.cs .

It uses the List<T>.BinarySearch by converting a collection of dictionary keys into a list. Then, using the answer here , we determine whether 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 that I did not check the effectiveness of this algorithm, but, at first glance, it seems quite good.

You can check it as follows:

 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)); 
+2
source

Source: https://habr.com/ru/post/973791/


All Articles