0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for answer! No wonder i couldn't save multiple values then with my tuple hehe.
A dictionary of lists of tuples, that makes my head hurt. Just make a proper class, so much easier to read.
@DavidG I would generally agree, especially if the type was exposed outside of the class. Otherwise, either a ValueTuple with named values (List<(DateTime date, double rate)> or a record would be a better choice than the older Tuple<DateTime, double>.
Let's be real, this is for an assignment. No way this would ever be used in a real life scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.