比较计算第一、第二、第三名

Compare and calculate first, second, and third place

我正在尝试找出计算第一名、第二名和第三名的最有效方法,用于一个简单的 C# 程序,目的是找到获胜者、第二名和第三名,并相应地显示他们的名字但是,对于这样一个简单的任务,我的代码似乎太大了。我是新手,我使用 If 语句来完成所需的计算,但我知道有更好的方法。谁能赐教一下?

这是我当前的代码,在意识到这将要占用的代码量后我停止了。

 private void calculateButton_Click(object sender, EventArgs e)
    {
        // Define Name and Time Variables
        string runnerone = runnerOneNameTextBox.Text;                       // Runner One Name
        string runnertwo = runnerTwoNameTextBox.Text;                       // Runner Two Name
        string runnerthree = runnerThreeNameTextBox.Text;                   // Runner Three Name
        double runnerOneTime = double.Parse(runnerOneTimeTextBox.Text);     // Runner One Time
        double runnerTwoTime = double.Parse(runnerTwoTimeTextBox.Text);     // Runner Two Time
        double runnerThreeTime = double.Parse(runnerThreeTimeTextBox.Text); // Runner Three Time

        //-------------------------------------------------------------------------
        // Start of the If statement to calculate who is first, second, and third. 
        //-------------------------------------------------------------------------

        // FIRST PLACE CODE: 
        if (runnerOneTime > runnerTwoTime && runnerOneTime > runnerThreeTime)  // Runner One is greater than everyone 
        {
            firstPlaceLabel.Text = runnerOneNameTextBox.Text;
            firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
        }
        else if (runnerOneTime == runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner one is equal to runner two
        {
            firstPlaceLabel.Text = runnerOneNameTextBox.Text;
            firstPlaceLabel.Text = runnerTwoNameTextBox.Text;
            firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
            firstPlaceTrophyLabel.Text = runnerTwoNameTextBox.Text;
        }
        else if (runnerOneTime > runnerTwoTime && runnerOneTime == runnerThreeTime) 
    }
}

}

你有一个包含三个跑步者的列表,所以让 .NET 列表排序功能来拯救你:

private class RunnersAndTimes
{
    public string Name {get};
    public double Time {get};

    public RunnersAndTimes(string name, double time)
    {
        Time = time;
        Name = name;
    }
}
...
private void calculateButton_Click(object sender, EventArgs e)
{
    var runnersAndTimes = new List<RunnersAndTimes> {
        new RunnersAndTimes(runnerOneNameTextBox.Text, 
                            double.Parse(runnerOneTimeTextBox.Text)),
        new RunnersAndTimes(runnerTwoNameTextBox.Text, 
                            double.Parse(runnerTwoTimeTextBox.Text)),
        new RunnersAndTimes(runnerThreeNameTextBox.Text, 
                            double.Parse(runnerThreeTimeTextBox.Text))
    };

    var orderedRunners = runnersAndTimes.OrderBy(runner => runner.Time).ToList();

    firstPlaceLabel.Text = orderedRunners[0];
    secondPlaceLabel.Text = orderedRunners[1];
    thirdPlaceLabel.Text = orderedRunners[2];
}