CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2005
    Posts
    180

    How To Modify An Element in the Dictionary Class?

    How To Modify An Element in the Dictionary Class?
    =======================================

    C# has this cool Dictionary class that you can use like a Hash Table. Is there a way of changing the value of an indexed element without resorting to removing it like this?

    int value = runningcount[city];
    runningcount.Remove(city);
    runningcount.Add(city, ++value);

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: How To Modify An Element in the Dictionary Class?

    According to this, you should be able to just write:
    ++runningcount[city];

    or
    runningcount[city]++;

    Did you try that?
    The indexer of the Dictionary class provides both get and set capabilities, even creates a new entry if the specified one doesn't exist already.
    Last edited by TheGreatCthulhu; August 18th, 2012 at 10:28 PM.

  3. #3
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: How To Modify An Element in the Dictionary Class?

    Yeah. As Cthulhu said, that should work. You can also update or add using this pattern:

    Code:
    if( dict.TryGetValue(key, out val) )
        dict[key] = newVal  //Update on key exist
    else
        dict.Add(key, newVal)  //Add on key not exist
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  4. #4
    Join Date
    Apr 2010
    Posts
    131

    Re: How To Modify An Element in the Dictionary Class?

    You can also use ContainsKey:
    Code:
    if(dict.ContainsKey(key)){
        dict[key]=value;
    }else{
        dict.Add(key,value);
    }
    That cat will get skinned one way or the other :-) Good luck!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured