user2262787
user2262787

Reputation: 77

Addition of value for each key in dictionary

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);
    }
}

Upvotes: 4

Views: 353

Answers (3)

phoog
phoog

Reputation: 43036

How about this, which handles lists of non-equal lengths:

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();

There is certainly a more efficient way to do this, but I am pretty sure it would require more typing.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 148980

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 }

Upvotes: 3

devdigital
devdigital

Reputation: 34349

Assuming the meter readings were changed to int, you can use LINQ:

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

Upvotes: 1

Related Questions