Find the range where the value lies in the dictionary

I have some data in this form (dictionary):

Value0  Text1
Value1  Text2
Value2  Text3
Value3  Text4
Value4  Text5

      

Now I need to go through an array that can have any random values.

foreach value in random array
{
    if value is between (value0 && value1)
    console.writeline(Text1)
    if value is between (value1 && value2)
    console.writeline(Text2)
    if value is between (value2 && value3)
    console.writeline(Text3)
    if value is between (value3 && value4)
    console.writeline(Text4)
}

      

The problem I am facing is that for each value in the array, I have to be able to determine which range it is (greater than 0 and less than 1), and hence get the corresponding text. But a dictionary is not a constant and can have any number of values, and therefore I cannot use these conditions as above. (For example: a dictionary may have a different entry Value5 Text6

)

What would be a decent way to do this?

+3


source to share


1 answer


You cannot do this with Dictionary<TKey,TValue>

, because it does not preserve ordered items. But you can use SortedDictionary<TKey, TValue>

(or SortedList<TKey, TValue>

) for this:



TValue GetValue<TKey, TValue>(SortedDictionary<TKey, TValue> dictionary, TKey key)
{
    var comparer = dictionary.Comparer;

    TValue result = default(TValue);

    foreach (var kvp in dictionary)
    {
        if (comparer.Compare(key, kvp.Key) < 0)
            return result;

        result = kvp.Value;
    }

    return result;
}

      

+3


source







All Articles