Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding more than one value to a Key in a Dictionary with Tuple Values

So, I’m writing a program that handles taxes.
I’ve got a Dictionary that is set up as following:

static Dictionary<Commodity, Tuple<DateTime, double>> _TaxRates = new Dictionary<Commodity, Tuple<DateTime, double>>();

Commodity is an Enum that handles different tax areas (Food, Alcohol, Transport etc.).
Now, I want to add a new tax rate, and the datetime that the tax rate was added.

So for instance, the Tax rate for Alcohol might have been 0,25% at 17:00, but at 17:25 it was 0,50% instead.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_TaxRates [commodity].Add(new Tuple<DateTime, double>(DateTime.Now, rate));

This gives me an error.

_TaxRates[commodity] =  Tuple.Create(DateTime.Now, rate);

And this seems to just overwrite the old value, meaning Alcohol has only ever had one Tax rate. Any helps or tips greatly appreciated.

"Full code" below:

            static Dictionary<Commodity, Tuple<DateTime, double>> _TaxRates= new Dictionary<Commodity, Tuple<DateTime, double>>();
        public void SetCustomTaxRate(Commodity commodity, double rate)
        {
            _TaxRates[commodity].Add(new Tuple<DateTime, double>(DateTime.Now, rate));

>Solution :

A Tuple only stores a single set of values. You want a Dictionary<Commodity, List<Tuple<DateTime, double>> instead.

private static readonly Dictionary<Commodity, List<Tuple<DateTime, double>> _TaxRates = new();

public void SetCustomTaxRate(Commodity commodity, double rate)
{
    if (!_TaxRates.TryGetValue(commodity, out var list))
    {
        list = new List<Tuple<DateTime, double>>();
        _TaxRates[commodity] = list;
    }
    
    list.Add(new Tuple<DateTime, double>(DateTime.Now, rate));
}

NB: Depending on your target framework, you may want to use a ValueTuple instead.
Tuple types – C# reference | Microsoft Docs

NB2: The code is not thread-safe. You should either lock the field, or use a ConcurrentDictionary<Commodity, List<(DateTime, double)>> instead.

NB3: Since you’re using DateTime.Now, you should watch out for daylight savings time issues. Consider using DateTime.UtcNow or switching to DateTimeOffset instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading