Adding a value for each key in a dictionary

I created a dictionary that has a meter number as a key and a list for a value. For example: Meter1 has an index value of 0, a value of 45, and an index value of 1. I wondered how to most effectively add an index of 0 for each of the counter numbers together? I am trying to get the maximum value added at a given index. Lists will be the same length. I have attached the code that I have to create a 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); } } 
+4
source share
3 answers

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

To get the maximum value in each index, try the following:

 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 create a new dictionary that preserves the maximum for each value in each index in the original dictionary.


Update

So you have this structure

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

And you want to calculate the maximum value of the total meter reading at any index. Suppose each List<double> is the same length, then, if I understand correctly, this will 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 an 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 } 
+3
source

Assuming the counter has been changed to int, you can use LINQ:

 var maxMeterValue = dictionary[myertNumber].Max(v => v); 
+1
source

How about this, which processes lists of unequal length:

 var maxLength = dictionary.Values.Max(readings => readings.Count); var sums = Enumerable.Range(0, maxLength) .Select(i => readings.Where(rs => i < rs.Count).Sum(rs => int.Parse(rs[i])); var maxSum = sums.Max(); 

Of course, there is a more efficient way to do this, but I'm sure more input will be required.

0
source

All Articles