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

Time:01-12

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.

_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));

CodePudding user response:

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.

  •  Tags:  
  • Related