GroupBy and Average with Lambda Expressions

by adam 7. October 2009 11:11

I was recently tasked with generating a string of averages based on a list of business objects.  The business object has a string property called VehicleName and a decimal property called StandardMpg.  The averages needed to be calculated per VehicleName, so this is to be what I group on.  This took me a few minutes to wrap my mind around, but once I got it, it seemed fairly simple. I thought it would be worth sharing with the rest of you:

string averages = string.Format("Avg: {0}",
    string.Join(" | ", gasMileageList
        .GroupBy(x => x.VehicleName)
        .Select(c => string.Format("{0} {1} MPG", c.Key, Math.Round(c.Average(x => x.StandardMpg), 1))).ToArray()));

The output will look something like: "Avg: bmw 21 MPG | kia 30 MPG"

Another option would be to dump the averages out to a list of objects, instead of a string.  To do this you can do:

private class MileageAverage
{
public string VehicleName { get; set; }
public decimal Average { get; set; }
}

...

var averages = gasMileageList
    .GroupBy(x => x.VehicleName)
    .Select(c => new MileageAverage { VehicleName = c.Key, Average = c.Average(x => x.StandardMpg) });


kick it on DotNetKicks.com

Tags: ,

C#

Comments

10/7/2009 3:47:13 PM #

trackback

GroupBy and Average with Lambda Expressions

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com | Reply

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About Adam

Adam Plocher is a professional .NET web/application developer in the Sacramento area.



Month List