Home > Enterprise >  Calculate average in Dictionary <string, List<double>> C#
Calculate average in Dictionary <string, List<double>> C#

Time:09-28

I need calculate the average of a List into a dictionary, I´m start using this syntax to access to the double List and gets the average but the compiler give an error, I´m new working with dictionarys, how is the correct syntax to access each double List and gets the average?

Here is the example of my code:

Dictionary<string, List<double>> SignalValues =
    new Dictionary<string, List<double>>();

var dSignalAvg = SignalValues
                 .Where(x => x.Key == "Key")
                 .Average(x => x.Value);

Thank you so much!

CodePudding user response:

If you are sure that the specific key exists in the dictionary then you can simply do:

var dSignalAvg = SignalValues["Key"].Average();

The code above will throw an exception if the dictionary doesn't have a key that equals "Key". If you want to check first, you can use TryGetValue like this:

double dSignalAvg = 0;

if (SignalValues.TryGetValue("Key", out List<double> signalList))
{
    dSignalAvg = signalList.Average();
}

CodePudding user response:

Like this?

Given a dictionary like this:

Dictionary<string,List<double>> values = new Dictionary<string,List<double>>();

Getting the average for a specific key is easy:

double avgValue = values
                  .Where( x => x.Key == "Key")
                  .Select( x => x.Value.Average() )
                  .FirstOrDefault()
                  ;

Or, if you want to reduce your dictionary to a dictionary of averages, it's just:

Dictionary<string,double> avgValues = values
                                      .ToDictionary(
                                        x => x.Key ,
                                        x => x.Value.Average()
                                      )
                                      ;
  • Related