Addition of value for each key in dictionary

c#, dictionary

Solution

I am trying to get the max added value at a given index.

To get the max value at a each index try this:

Dictionary<string, List<double>> dictionary = ... // NOTE: use some numeric type
Dictionary<string, double> maxima = dictionary.ToDictionary(p => p.Key, p => p.Value.Max());

This will produce a new dictionary which stores the maximum for every value at each index in the source dictionary.

Update

So you have this structure

"Meter1", [ 15, 5, 10 ]
"Meter2", [ 10, 50, 20 ]

And you want to compute the maximum value of the sum of meter readings at any index. Let's assume that each `List<double>` is the same length, then if I'm understanding correctly, that would be:

Dictionary<string, List<double>> dictionary = ...
var length = dictionary.First().Value.Length;
var maximum = Enumerable.Range(0, length)
                        .Select(i => dictionary.Values.Select(d => d[i]).Sum())
                        .Max(); // 55

If you also want to get the index where this is the maximum you can use this:

var result =
    (from i in Enumerable.Range(0, length)
     let s = dictionary.Values.Select(d => d[i]).Sum()
     orderby s descending
     select new { Index = i, Sum = s })
    .First(); // { Index = 1, Sum = 55 }

Problem

I have created a dictionary that has a meter number as the key and a list for the value. For example: Meter1 has index 0 value 45 and index 1 value 65. I was wondering the most efficient way to add index 0 for each of the meter numbers together? I am trying to get the max added value at a given index. The lists will be the same length. I have attached the code I have to create the dictionary. ``` Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>(); foreach (string ertNumber in ertNumberList) { if (!dictionary.ContainsKey(ertNumber)) { List<string> meterReadings = new List<string>(); meterReadings = getValuesFromOID(ertNumber); dictionary.Add(ertNumber, meterReadings); } } ```

Original source