C# WPF:使用列表框中的按钮查找最大值

C# WPF : Find largest value with a button in ListBox

这可能是一件小事,但我找不到答案。

我想要的是,当您将一些数字添加到列表框中时,当您按下 "Largest Button" 时,它将显示列表中的最大数字。

图片如下:Image Link

这是代码。

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
        ListBoxItem newItem = new ListBoxItem();
        newItem.Content = addNumberTextBox.Text;
        numberListBox.Items.Add(newItem);
    }

    private void sumButton_Click(object sender, RoutedEventArgs e)
    {
        int sum = 0;
        foreach (ListBoxItem item in numberListBox.Items)
        {
            sum += Convert.ToInt32(item.Content);
        }
        sumTextBox.Text = Convert.ToString(sum);
    }

    private void largestButton_Click(object sender, RoutedEventArgs e)
    {
       ????
    }
}

你可以这样做:

int highestNum = 0;

foreach (ListBoxItem item in numberListBox.Items)
{
    if (item > highestNum)
    {
        highestNum = item;
    }
}

highestNumTextbox.text = highestNum;
    private void largestButton_Click(object sender, RoutedEventArgs e)
    {
          int largest= 0;
          foreach (ListBoxItem item in numberListBox.Items)
          {
               if (Convert.ToInt32(item.Content)>largest)
                  largest=Convert.ToInt32(item.Content);

          }
          largestTextBox.Text = Convert.ToString(largest);
     }

使用 Linq 很简单,

var items = numberListBox.Items.OfType<ListBoxItem>;
var numbers = items.Select(x => Convert.ToInt32(x.Content));
var largest = numbers.Max();