Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

Posted by JP on November 13, 2011


Lambda Expressions Extension Methods Series 10 – Min, Max, Sum, Average

The Extension Methods also include the following 4 calculation methods – Min, Max, Sum and Average() for calculating the minimum value, maximum value, sum and average respectively.

Method

Description

Min()

Calculates the minimum value in the series

Max()

Calculates the maximum value in the series

Sum()

Calculates the sum of the values

Average()

Calculates the average of the values

The above methods saves a lot of time and code by discarding the need of creating a variable and for loop to iterate through the elements to find the Minimum, Maximum, Sum and Average of the items.

Example

The sample list would be a list of integers from 1 to 6.

public InitializeLIst()

{

InitializeComponent();

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

The test code will be as following:

private void MinMaxSumAvgButton_Click(object sender, EventArgs e)

{

int min = _list.Min();

int max = _list.Max();

int sum = _list.Sum();

double average = _list.Average();

string message = “Min={0}\nMax={1}\nSum={2}\nAverage={3}”;

MessageBox.Show(string.Format(message, min, max, sum, average));

}

On execution of the code above we can see the output as below:

Extension Method Snapshot

You can find the snapshot of Min() method usage as provided by Visual Studio.

You can find the snapshot of Max() method usage as provided by Visual Studio.

You can find the snapshot of Sum() method usage as provided by Visual Studio.

You can find the snapshot of Average() method usage as provided by Visual Studio.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s