简体   繁体   中英

C# get smallest and largest values from a list

I need to go through a list and find the largest and smallest values. The list is populated based on the input from a user entering information into a form text box. Then each time that I click on a button to calculate in my form it runs code that does calculations and puts decimals into listProfit. I have looked all over the place and tried using .Sort() but that causes a system error.

This is the error I am getting.

An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Collection was modified; enumeration operation may not execute.

error highlights the "in" in my foreach loop.

//list of each order total
List<decimal> listProfit = new List<decimal>(); 

    foreach(int item in listProfit)
                    {
                        listProfit.Sort();
                        decimal smallest = listProfit[0];
                        decimal largest = listProfit[listProfit.Count - 1];
                        SmallTxt.Text = smallest.ToString("c");
                        LargestTxt.Text = largest.ToString("c");
                    }

Use Min and Max from System.Linq:

var min = listProfit.Min();
var max = listProfit.Max();

You don't need to iterate at all. You can just say like below, if you want to continue with sorting the list. Else, try using Min() and Max() LINQ extension methods to get those directly

  listProfit.Sort();
  decimal smallest = listProfit[0];
  decimal largest = listProfit[listProfit.Count - 1];

To get the minimum value use

SmallTxt.text = listProfit.Min().ToString("c");

To get the max

LargestTxt.Text = listProfit.Max().ToString("c");

No need to sort the list, however be aware that both of these operations enumerate the whole list.

Based on your question I am assuming you are a beginner. Consider KISS and think how you would do this without LINQ.

// declare list
var listProfit = new List<decimal>(); 
// populate list 
listProfit.Add(300.5m); //etc

// initial values for min and max
decimal min = Decimal.MaxValue;
decimal max = Decimal.MinValue;

// loop through the list
for (int i = 0; i < listProfit.Count; i++)
{
    // is the current item smaller than min? 
    if (listProfit[i] < min) 
        // if yes, set min to that value
        min = listProfit[i];
    // is the current value greater than max?
    if (listProfit[i] > max) 
        // if yes, set max to that value
        max = listProfit[i];
}

// you are now outside of the for loop, with your min and max values populated

If you're sorting the list beforehand, @Rahul's answer is the way to go.

Please see Input form

 List<decimal> lstProfit = new List<decimal>();
    private void button1_Click(object sender, EventArgs e)
    {
        lstProfit.Add(Convert.ToDecimal(textBox1.Text));

        textBox2.Text = lstProfit.Min().ToString();
        textBox3.Text = lstProfit.Max().ToString();
    }

Please see input/output form

explanation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM