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

烈酒焚心 提交于 2019-12-21 07:08:07

问题


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?


回答1:


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.




回答2:


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

myList.Sum(x => x.Value) - myList.First().Value;



回答3:


Easy enough to do using LINQ:

var dict = new Dictionary<string, decimal>();

dict.Add("A", 1.5m); // This value will be skipped
dict.Add("B", 2.7m);
dict.Add("C", 1.3m);
dict.Add("D", 3.9m);

var total = dict.Skip(1).Sum(v => v.Value);

Console.WriteLine(total);



回答4:


Skip the first element thusly;

dict.Skip(1).Sum(ix => ix.Value);


来源:https://stackoverflow.com/questions/8128477/how-to-calculate-the-sum-of-all-values-in-a-dictionary-excluding-the-first-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!