HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Any way of simplifying the following two short snippets regarding Dictionary?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theshortsnippetsanyregardingwayfollowingtwosimplifyingdictionary

Problem

Example 1

if (myList.ContainsKey(myKey))
{
    myList[myKey]++;
}
else
{
    myList.Add(myKey,1);
}


Example 2

Where(x => 
(myList.ContainsKey(x.Key) ? x.Value - myList[x.Key] : x.Value) >


myList is Dictionary.

Is there any way or existing method of simplifying or normalizing the code?

Update

Now I've learned Python and came across defaultdict:

-
Analogue of Python's defaultdict?

-
Dictionary returning a default value if the key does not exist

Solution

For example, you can write your own extenession method for this operation and use it everywhere. Something like this

public static void SetOrIncrement(this Dictionary dictionary, K key)
    {
        int value;
        if (dictionary.TryGetValue(key, out value))
        {
            dictionary[key] = value + 1;
        }
        else
        {
            dictionary[key] = 1;
        }
    }


And then just use it in the following way:

myList.SetOrIncrement(myKey);

Code Snippets

public static void SetOrIncrement<K>(this Dictionary<K, int> dictionary, K key)
    {
        int value;
        if (dictionary.TryGetValue(key, out value))
        {
            dictionary[key] = value + 1;
        }
        else
        {
            dictionary[key] = 1;
        }
    }
myList.SetOrIncrement(myKey);

Context

StackExchange Code Review Q#4342, answer score: 7

Revisions (0)

No revisions yet.