Reputation: 143
This is probably straightforward but searching at stack overflow didnt give me desired results.
I have a simple dictionary defined as
var GetAllInjData = new Dictionary<double, List<double>>();
All I want to do is the pick the list of values at each key from the dict and add them up to get a single value!
Upvotes: 0
Views: 78
Reputation: 1307
GetAllInjData.SelectMany(a => a.Value).Sum();
Edit after seeing your loop
IEnumerable<double> FieldProd = GetAllInjData.Select(a => a.Value.Sum());
Upvotes: 2
Reputation: 34421
Try this
Dictionary<double, List<double>> GetAllInjData = new Dictionary<double, List<double>>() {
{1, new List<double>() {1,2,3,4,5,6}},
{2, new List<double>() {11,12,13,14,15,16}},
{3, new List<double>() {21,22,23,24,25,26}}
};
double results = GetAllInjData[2].Sum();
Upvotes: 0
Reputation: 4135
Like so:
var sums =
from keyVal in GetAllInjData
select new
{
ForKey = keyVal.Key,
SumIs = keyVal.Value.Sum()
};
foreach(var sum in sums)
Debug.WriteLine($"Key: {sum.ForKey} Sum: {sum.SumIs}");
Upvotes: 0
Reputation: 1893
Try this:
double key = 1; //for example
double sum = 0.0;
GetAllInjData[key].ForEach(x => sum += x);
Upvotes: 0
Reputation: 152491
If you want the sum for each key then you can use Select
to project each key-value pair to a new type with the key and the sum of the values as properties:
GetAllInjData.Select(kvp => new {Key = kvp.Key, Value = kvp.Value.Sum()})
Upvotes: 0