Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the sum of all values in a dictionary excluding the first item's value?

Tags:

c#

linq

c#-3.0

I have a dictionary of (string, decimal) and need to calculate the sum of all the Values (decimal values) starting from the second item. Is it achievable using LINQ?

like image 636
Jyina Avatar asked Nov 14 '11 21:11

Jyina


People also ask

How do you sum all values in a dictionary?

You can get a generator of all the values in the dictionary, then cast it to a list and use the sum() function to get the sum of all the values.

How do you get the sum of all the values in a dictionary python?

To sum all values in a Python dictionary, use sum() and a list representation of the dictionary values obtained with my_dict. values() and using list() for the conversion.

How do I store multiple values in a key python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.


2 Answers

Very achievable using LINQ:

myDict.Skip(1).Sum(x => x.Value); 

However, the standard Dictionary class doesn't guarantee ordering of items, so the "first" item can be anything.

like image 190
Oded Avatar answered Sep 21 '22 00:09

Oded


Why not just sum them all up, then subtract the first item?

myList.Sum(x => x.Value) - myList.First().Value; 
like image 39
Adam V Avatar answered Sep 23 '22 00:09

Adam V