.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

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

Posted By:Jean Paul       Posted Date: May 16, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

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.
 

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.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend