Hi guys,

I am trying to write a program which picks the closest number possible out of a dictionary.

The dictionary contains 50 doubles values, and I use a random double to pick the number i want to get the closest to if that makes sense.

Currently I am using linq to pick the first one which is less or equal to the random number. The problem I have found with this is that it is not reaching numbers which are closer and its most certainly picks the same key all the time. I have also tried the SkipWhile method but I have not seen much of a difference. Also tried to 'shuffle' the dictionary before finding the closest, which as help as now im not getting the same value.

Just curious, is there is a method I'm not trying which is better than what I am currently doing.

Perhaps if you use a list instead of a dictionary. You can then order by value, find the one that is less or equal, and then take the next one if the difference between the value and your chosen number is less than the current one.

Indeed, as priteas pointed out, a List and sorting is more appropriate here.
But if you must use a dictionary, this might help.

Just curious what kind of application needs to choose one of 50 doubles without going over? Is this some kind of guessing game?

I wish to keep it as a dictionary as the Keys will be used later on. I managed to write a new method using Linq which get a closer value.

It possibly might be for a game later on, once i decided to install unity again. However, for now it just me getting used to Linq.

This question has already been answered. Start a new discussion instead.