Ken'ichi Matsuyama
Ken'ichi Matsuyama

Reputation: 369

Adding items in dictionary

I am having problem on how to add items in my dictionary.

        int y = 0;
        foreach (var entry in fun)
        {
                entry.Value += entry.Value;
                y = entry.Value;
        }

This doesn't work. I want to have a sum of all items in my dictionary:

var fun = new Dictionary<string, int>();

For example, the string is Hello fun fun, so dictinary will show Hello: 1, Fun: 2, and sum is 3. And I want that 3 to be counted.

Upvotes: 0

Views: 68

Answers (3)

Chief Wiggum
Chief Wiggum

Reputation: 2934

There are more elegant LINQ solutions, but this should do the trick:

    int y = 0;
    foreach (var entry in fun)
    {
            y += entry.Value;
    }

As mentioned by @Rotem in the comments it's as easy as:

fun.Values.Sum()

Upvotes: 2

galenus
galenus

Reputation: 2127

Your problem is you are trying to modify Value property of KeyValuePair type, which is read-only.

Better use LINQ:

fun.Aggregate(0, (sum, keyValue) => sum + keyValue.Value);

Upvotes: 0

dotnetstep
dotnetstep

Reputation: 17485

This is what you have to do.

 foreach (var entry in fun)
        {

                y = y + entry.Value;
        }

Upvotes: 1

Related Questions