I have Dictionary<int,string>
with ascending keys like this:
var myDictionary = new Dictionary<int,string>
{
{750,"one"},
{1500,"two"},
{2500,"three"},
{5000,"four"},
{10000,"five"},
{25000,"six"}
}
I have var myValue = 3000.52
I need to find the largest myDictionary
key that is smaller than my value. In this case, I need to return 2500.
I have tried:
foreach (var key in myDictionary.Keys.Where(key => key <= myValue))
{
}
But, as you would expect, all smaller values also match.
How do I find the largest key that is smaller than my search value?
In Python to find the highest value in a dictionary, we can use the concept of key. get() method. By using the built-in max() method. It is provided with the 'alpha_dict' variable to obtain the highest value from and to return the key from the given dictionary with the highest value, the dict.
get() method is used in Python to retrieve a value from a dictionary. dict. get() returns None by default if the key you specify cannot be found. With this method, you can specify a second parameter that will return a custom default value if a key is not found.
The maximum capacity of a dictionary is up to 2 billion elements on a 64-bit system by setting the enabled attribute of the gcAllowVeryLargeObjects configuration element to true in the run-time environment.
Using LinQ is the simplest way I think:
int myKey = myDictionary.Where(x => x.Key < myValue)
.OrderByDescending(x => x.Key)
.First().Key;
You could create a List<int>
from the dictionary keys. I would store this list if you need to lookup it often. Then you can use List.BinarySearch
to find the nearest key:
int key = 3000;
var keys = new List<int>(myDictionary.Keys);
// keys.Sort(); if it was not already sorted
var index = keys.BinarySearch(key);
if (index >= 0)
{
// dictionary contains this key
}
else
{
int nextSmaller = ~index - 1;
string valueOfNextSmaller = myDictionary[keys[nextSmaller]]; // three
}
BinarySearch
returns the zero-based index of item in the sorted List<T>
, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
Giorgos' answer is the best you'll be able to do working with Dictionary
, but it will be slow because this will search the entire keyspace. If you want something fast, the C5 collections library has a lot of features lacking in .NET. You can do this:
TreeDictionary<K,V> dict;
var last = dict.RangeTo(myValue).Backwards().First();
Which will execute in O(log n), much more efficient as your dictionary's size grows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With