C# Looping through Dictionary and summing values for Keys -
i have dictionary<string, decimal?>
, , able sum decimals distinct string. have below inputs in dictionary,
"1", 20.00 "1", 35.00 "2", 10.00 "3", 15.00 "3", 30.00
i following output new dictionary
"1", 55.00 "2", 10.00 "3", 45.00
i'm guessing
foreach(var item in dictionary) { newdictionary.add(not sure go here, maybe sort of linq query distinct , sum?); }
the keys in dictionary can't repeated, 2 first entries won't fit in dictionary.
i think may have list of objects can loop, can use dictionary store total each "key"
something like
dictionary<string, double> totals = new dictionary<string, double>(); list<tuple<string, double>> entries = new list<tuple<string, double>>() { new tuple<string, double>("1",20.00), new tuple<string, double>("1",35.00), new tuple<string, double>("2",10.00), new tuple<string, double>("3",15.00), new tuple<string, double>("3",30.00) }; foreach (var e in entries) { if (!totals.keys.contains(e.item1)) { totals[e.item1] = 0; } totals[e.item1] += e.item2; }
Comments
Post a Comment