-3

Is it possible to get the mean, median and stdev result from the list of list. Here is my initial code that needs to compute:

var myList = new List<List<double>>();

myList.Add(new List<double> { 1, 3, 6, 8});
myList.Add(new List<double> { 1, 2, 3, 4});
myList.Add(new List<double> { 1, 4, 8, 12});

And expected result is to get the mean, median, and stdev of first and last index only:

Mean:   1, 8
Median: 1, 8
Stdev:  0, 3.265986324

I tried to loop the list to get the average but not sure if this is the best way:

 foreach(var i in myList )
            {
                Console.WriteLine(i[0].Average());
            }

Any suggestion/comments TIA

Rock n' Roll
  • 924
  • 1
  • 12
  • 31

2 Answers2

2

This will get you started by showing how to calculate the Average. Note the use of First or Last to get the first / last entry from each of the sub-lists.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            var myList = new List<List<double>>();

            myList.Add(new List<double> { 1, 3, 6, 8 });
            myList.Add(new List<double> { 1, 2, 3, 4 });
            myList.Add(new List<double> { 1, 4, 8, 12 });

            var averageFirst= myList.Select(z => z.First()).Average();
            var averageLast = myList.Select(z => z.Last()).Average();

            Console.WriteLine(averageFirst);
            Console.WriteLine(averageLast);

            Console.ReadLine();
        }
    }
}
mjwills
  • 21,750
  • 6
  • 36
  • 59
0

I'll join forces with @mjwills (first and last)

Which is to say,

var listOfFirstValues = myList.Select(z => z.First()).ToList();
var listOfLastValues = myList.Select(z => z.Last()).ToList();

Mean

var mean = myList.Average(); 

Median The middle of a sorted list of numbers

public double Median(List<double> numbers)
{
   if (numbers.Count == 0)
      return 0;

   numbers = numbers.OrderBy(n=>n).ToList(); 

   var halfIndex = numbers.Count()/2; 

   if (numbers.Count() % 2 == 0)
     return (numbers[halfIndex] + numbers[halfIndex - 1]) / 2.0;

   return numbers[halfIndex];
}

Standard Deviation a quantity expressing by how much the members of a group differ from the mean value for the group

private double CalculateStdDev(List<double> values)
{  
   if (values.Count == 0)
      return 0;

   var avg = values.Average();  
   var sum = values.Sum(d => Math.Pow(d - avg, 2));   
   return Math.Sqrt(sum / (values.Count()-1));
}

Note : Totally untested, and lacking any sanity checks

halfer
  • 18,701
  • 13
  • 79
  • 158
TheGeneral
  • 69,477
  • 8
  • 65
  • 107