Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set all negative values in a dictionary to be zero?

Tags:

c#

dictionary

Working on a lil' c# browser game where I use this dictionary to keep track on several resources in the game:

public Dictionary <String, int> resource = new Dictionary<string,int>();

Amoungst those, "gold", which changes for each tick.

protected void timerMinute_Tick(object sender, EventArgs e)
{
resource["gold"] += (resProduction["gold"] - resConsumption["gold"])
}

Now, if consumption is greater than production, the number decreases. I want to deny the resource from becoming negative. I know that I can do this for each tick:

if (resource["gold"] < 0)
{
resource["gold"] = 0;
}

However, I have many many more resources to keep track on, so while I could write the aforementioned code for each, I just wondered if someone had a clever way to check all values in the dictionary resource, and turn any negatives into zero.

Edit: Thanks for all the great suggestions to the problem here! As a newbie with c#, I'm not quite familiar with it all ^^

like image 431
Zaffaro Avatar asked Jan 20 '26 00:01

Zaffaro


1 Answers

You could make your own dictionary class that ensures the values are non-negative. This is a simple example, but you could make it generic and extensible pretty easily.

public class ValidatedDictionary : IDictionary<string, int>
{
    private Dictionary<string, int> _dict = new Dictionary<string, int>();
    protected virtual int Validate(int value)
    {
        return Math.Max(0, value);
    }
    public void Add(string key, int value)
    {
        _dict.Add(key, Validate(value));
    }

    public bool ContainsKey(string key)
    {
        return _dict.ContainsKey(key);
    }
    // and so on: anywhere that you take in a value, pass it through Validate
like image 104
Tim S. Avatar answered Jan 22 '26 14:01

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!