1

Hello I would like to ask you is there a way to calculate average and std deviation at the same time with LINQ.

var players = new List<Player>
{
    new Player { Name = "Alex", Team = "A", Score = 10 },
    new Player { Name = "Anna", Team = "A", Score = 20 },
    new Player { Name = "Luke", Team = "L", Score = 60 },
    new Player { Name = "Lucy", Team = "L", Score = 40 },
};

var teamAverageScores =
    from player in players
    group player by player.Team into playerGroup
    select new
    {
        Team = playerGroup.Key,
        AverageScore = playerGroup.Average(x => x.Score),
    };

I would like to calculate in this example the STDev for the score and return two different list one for the average and one for the standard deviation.

Expected result for AverageScore:

{ Team = "A", AverageScore = 15.0 } 
{ Team = "L", AverageScore = 50.0 } 

And for std dev:

{ Team = "A", STDScore = 5.0 } 
{ Team = "L", STDScore = 10.0 }
4
  • Can you show what would be your desired result? Apr 1, 2020 at 9:46
  • I would like to have a list for average { Team = "A", AverageScore = 15.0 } // { Team = "L", AverageScore = 50.0 } and list for std dev { Team = "A", STDScore = 2.0 } // { Team = "L", STDScore = 3.0 } this is just an example not precise values Apr 1, 2020 at 9:47
  • Are you sure about the values of STDDev? I have found a solution for you, but in my calculations I am getting 5 and 10 as STDDev based on your inputs. Apr 1, 2020 at 10:00
  • yeah that's what i mentioned it's only for the example so it's not a correct output, but please if u have a solution i am glad that u can share it Apr 1, 2020 at 10:04

3 Answers 3

2

An easy solution would be to use the NuGet package LinqStatistics to calculate the standard deviation scores, and Enumerable.Average() from LINQ to calculate the average scores. If you don't like using external libraries, then @Salah Akbari's solution will be a better fit. I thought it was a good idea to bring this library up, since I've used it in the past with no problems.

using LinqStatistics;

// Other code

// Class that stores results from query
// Might be cleaner than using an anonymous class
public class Result
{
    public string Team { get; set; }
    public double Average { get; set; }
    public double StdDev { get; set; }
}

var teamAverageScores = players
    .GroupBy(player => player.Team)
    .Select(grp => new Result
    {
         Team = grp.Key,
         Average = grp.Average(player => player.Score),
         StdDev = grp.StandardDeviation(player => player.Score)
    });

Try on dotnetfiddle.net

Note: The above uses LINQ method syntax fully, instead of query syntax. You can read about the differences between these different syntax types at MSDN. Using either comes down to preference.

3
  • 1
    thanks for the response but I am avoiding using external libraries Apr 1, 2020 at 12:05
  • The OP is using Entity Framework. Their source is not actually a List<Player>, so most probably the StandardDeviation operator will not be recognized by the EF machinery. Apr 1, 2020 at 13:35
  • @TheodorZoulias Yeah. I don't have an EF Core environment set up so Its hard for me to test, but your probably right.
    – RoadRunner
    Apr 1, 2020 at 14:55
2

Based on this, you need to use an extension method like this:

public static class ExtensionsClass
{
    public static double CalculateStdDev(this IEnumerable<double> values)
    {
        double ret = 0;
        int count = values.Count();
        if (count > 1)
        {
            //Compute the Average
            double avg = values.Average();

            //Perform the Sum of (value-avg)^2
            double sum = values.Sum(d => (d - avg) * (d - avg));

            //Put it all together
            ret = Math.Sqrt(sum / count);
        }
        return ret;
    }
}

Then you can do:

var teamAverageScores =
     from player in players
     group player by player.Team into playerGroup
     select new
     {
         Team = playerGroup.Key,
         AverageScore = playerGroup.Average(c => c.Score),
         STDev = playerGroup.Select(c => c.Score).CalculateStdDev(),
     };
12
  • Extension methods of IEnumerable<T> should not enumerate the source more than once, because it is possible (and quite frequent) that the underlying data are not stored in memory but are fetched from a database (or from the filesystem or from a web API). An easy fix is to replace IEnumerable<int> with ICollection<int>, since a container of this type is most certainly stored in memory. Apr 1, 2020 at 10:24
  • System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Double StdDev(System.Collections.Generic.IEnumerable`1[System.Double])' method, and this method cannot be translated into a store expression.' This is what i am getting on the run time Apr 1, 2020 at 10:51
  • @ZaatourWadi Use ToList() after Select and before Calculate. Apr 1, 2020 at 10:56
  • 2
    Can you please update the question to include that? That information is quite important as Salah has answered this question believing that it is a simple LINQ query (Please correct me if I'm wrong @SalahAkbari) and such a query won't work in Entity Framework.
    – ColinM
    Apr 1, 2020 at 11:15
  • 2
    @ColinM Yes, that's why I have suggested to use ToList() in order to do the further operation in memory. However I can't guarantee the performance in this approach. Apr 1, 2020 at 11:17
0

I found the solution after several tries

var teamAverageScores =
        from player in players
        group player by player.Team into playerGroup
        select new
        {
            Team = playerGroup.Key,
            AverageScore = playerGroup.Average(c => c.Score),
            STDev =  (playerGroup.Count() == 1) ? 0 : Math.Sqrt(playerGroup.Sum(b => Math.Pow(playerGroup.Score - playerGroup.Average(c => c.Score), 2)) / (g.Count() - 1)),,
        };
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.