tags:

views:

61

answers:

3

Hi all,

This might be a very silly / stupid question, but, my defence is that I am a beginner!

Suppose I have a dictionary in c# :

Dictionary<int,string> D = new Dictionary<int,string>();

If I wanted to add all values (which is string) instead of looping and appending all values to a stringBuilder, i do:

string.Join(",",D.values.ToArray());

which works fine. Now, If I want to add all the keys (which is int) to a total, is there a similar way to do this? I dont want to loop through (unless that is the only way) each item and add them. I am not talking about D.Add() which adds a new item, but Math addition, like Key 1 + key 2 etc..

Thanks!

+4  A: 
D.Keys.Sum();

will do just what you think it should

Sruly
thanks, this was very silly question i suppose!
iamserious
+2  A: 

By its very definition, adding together numbers requires that you "loop through each one of them".

var total = D.Keys.Sum()
Jamiec
+1  A: 
int x = D.Keys.Sum(); or D.Keys.ToList<int>().Sum()

actually you dont need to use to list at all

Stacker