问题
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