Getting pairs of keys and values ​​from a dictionary

advertisements

I want to store diameter of euro coins inside a class and using a method in that class to get value(worth) of a coin by its diameter.

First I am not sure using a class and building its dictionary on initializaition is a good idea or not so If you know a better way please let me now.

Second, I wrote the code for this class like this:

class EuroCoinSpecs
{
    public Dictionary<double, decimal> CoinsDiameters;

    public EuroCoinSpecs()
    {
        CoinsDiameters = new Dictionary<double, decimal>
                        {
                            {25.75, 2.00m},
                            {23.25, 1.00m},
                            {24.25, 0.50m},
                            {22.25, 0.20m},
                            {19.75, 0.10m},
                            {21.25, 0.05m},
                            {18.75, 0.02m},
                            {16.25, 0.01m}
                        };
    }

    public decimal GetValueForDiameter(double diameter)
    {
        return CoinsDiameters.FirstOrDefault(x => x.Key == diameter);
    }
}

The problem is the code in GetValueForDiameter does not compile because of this error:

Cannot implicitly convert type 'System.Collections.Generic.KeyValuePair<double,decimal>' to 'decimal'

I tried different ways but it does not want to work. What can be the problem?


Others have given the way of fetching using FirstOrDefault - but it seems pretty pointless to me. Why not use the fact that you've got a dictionary, which is designed to perform key lookups for you?

public decimal GetValueForDiameter(double diameter)
{
    decimal ret;
    // This will set ret to 0m if the key isn't found.
    CoinsDiameters.TryGetValue(diameter, out ret);
    return ret;
}

Having said all of that, I would strongly recommend that you don't perform equality operations on double values like this. It'll work okay in the cases you've given, but as soon as you start using any sort of arithmetic, you could well end up causing problems.