windows 表单应用程序中数组的最小元素问题

Problem with minimum element of an array in windows form application

我正在学习如何创建简单的 .NET 应用程序。在此应用程序中,我在 TextBox 的整数数组中添加数字,并在 ListBox 中显示此数组中的最大和最小数字。问题是,当我使用 Min 方法找到最小数量时,它总是给我 0,但是 Max 方法工作正常

    public partial class Form1 : Form
    {
        // ...

        int[] array = new int[100];
        int counter = 0;
        private void button1_Click_1(object sender, EventArgs e)
        {
            for (int i = 0; i <= counter; i++)
            {
                array[i] = Convert.ToInt32(txtInsertNumber.Text);
            }
            counter++;
        }

        private void btnShowMinMax_Click_1(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            int max = array.Max();
            int min = array.Min();

            int maxIndex = Array.IndexOf(array, max);
            int minIndex = Array.IndexOf(array, min);

            listBox1.Items.Add(array[maxIndex] + " " + array[minIndex]);
        }
    }

您的数组 int[] array = new int[100]; 初始化为 100 个整数,默认值为 0。这就是最小值为 0 的原因。

解决方案是使用 Nullable<int> 数组来区分 "no value" null 与实际值。示例:

int[] a = new int[50];
Console.WriteLine(a.Min()); // prints "0"

Nullable<int>[] b = new Nullable<int>[100];
Console.WriteLine(b.Min()); // prints ""

此外,您可以使用具有预定义大小的 List<int>

    static void Main(string[] args)
    {
        var list = new List<int>(10);
        list.Add(1);
        list.Add(2);

        var min = list.Min(); //  will be 1
        var max = list.Max(); // will be 2 
    }