Modi
Modi

Reputation: 143

c# dictionary - Add values(list) stored at one key

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

Answers (6)

Tony
Tony

Reputation: 1307

GetAllInjData.SelectMany(a => a.Value).Sum();

Edit after seeing your loop

IEnumerable<double> FieldProd = GetAllInjData.Select(a => a.Value.Sum());

Upvotes: 2

jdweng
jdweng

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

Colin
Colin

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

RomCoo
RomCoo

Reputation: 1893

Try this:

double key = 1; //for example
double sum = 0.0;
GetAllInjData[key].ForEach(x => sum += x);

Upvotes: 0

D Stanley
D Stanley

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

Dan Forbes
Dan Forbes

Reputation: 2824

I think you can do this with LINQ:

GetAllInjData[<key>].Sum();

Upvotes: 0

Related Questions