Cipher
Cipher

Reputation: 6082

Find which range does the value lie in a dictionary

I have some data in this form (dictionary):

Value0  Text1
Value1  Text2
Value2  Text3
Value3  Text4
Value4  Text5

I now have to loop through an array which may 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 here is that the for each value of the array, I should be able to detect what range it is (greater than value 0 and lesser than value 1), and hence get the corresponding text. But, the dictionary is not a constant and can have any number of values and hence I cannot these if conditions as above. (For eg: the dictionary might have another entry Value5 Text6)

what would be a decent way to do this?

Upvotes: 3

Views: 392

Answers (1)

svick
svick

Reputation: 244767

You can't do this using a Dictionary<TKey,TValue>, because it doesn't keep the items in it ordered. But you can use a SortedDictionary<TKey, TValue> (or a SortedList<TKey, TValue>) to do 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;
}

Upvotes: 3

Related Questions