简体   繁体   中英

c# how to find the smallest and largest value in a list box

Could anyone assist me with a section of my C# program that I can't seem to solve.

I using C# windows form application. I have created a program that generates random non-duplicate numbers. The range of numbers is between 0 - 100 and displays 30 values within the range in a list box.

Note: The list box is not declared with an array as the list box is an array itself and I don't want to declare new arrays.

I am having a bit of trouble in finding the smallest and largest value within the list box and output the result to a label. But with my current code it is displaying only the last item which is at the bottom of the list box.

        int smallestValue = 0;
        int largestValue = 0;


        for (int i = 0; i < lstNumberList.Items.Count; i++)
        {
            if(i > largestValue)
            {
                largestValue = i;
                lblMaxResult.Text = lstNumberList.Items[largestValue].ToString();

            }
            if (i < smallestValue)
            {
                smallestValue = i;
                lblMinResult.Text = lstNumberList.Items[smallestValue].ToString();
            }
        }

In order to avoid such errors (treating index i as a value int.Parse(lstNumberList.Items[i].ToString) ) you may want to change for loop into foreach one:

int smallestValue = int.MaxValue;
int largestValue = int.MinValue;

foreach (var item in lstNumberList.Items) {
  int value = int.Parse(item.ToString());

  if (value > largestValue)
    largestValue = value;

  if (value < smallestValue) 
    smallestValue = value;
}

// Let's push UI out of the loop (we want min and to be printed once)
lblMaxResult.Text = $"{largestValue}";
lblMinResult.Text = $"{smallestValue}";

In Real World, when we want to query , we often use Linq :

  using System.Linq;

 ...

  var data = lstNumberList
    .Items
    .OfType<String>()
    .Select(item => int.Parse(item));

  lblMaxResult.Text = $"{data.Max()}";
  lblMinResult.Text = $"{data.Min()}";

Fixed your solution:

    var smallestValue = int.MaxValue;
    var largestValue = int.MinValue;

    for (int i = 0; i < lstNumberList.Items.Count; i++)
    {
        var value = (int)lstNumberList.Items[i];
        if(value > largestValue)
        {
            largestValue = value;
            lblMaxResult.Text = largestValue.ToString();

        }
        if (value < smallestValue)
        {
            smallestValue = value;
            lblMinResult.Text = smallestValue.ToString();
        }
    }

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