简体   繁体   English

比较时如何获取变量?

[英]How to get variable as a result of a comparison?

I have a windows form and a simple horce racing application. 我有一个Windows窗体和一个简单的Horce Racing应用程序。 My horses are pictureBox controls. 我的马是pictureBox控件。 I want to print the winner by checking who is more far away from starting point. 我想通过检查谁离起点更远来打印赢家。

    control aa.left = (unknown integer value);
    control bb.left = (unknown integer value);
    control cc.left = (unknown integer value);
  • If first one has the biggest value, I want to print "First one is champion" 如果第一个具有最大价值,我要打印“第一个是冠军”
  • If second one has the biggest value, I want to print"Second one is champion" 如果第二个具有最大价值,我要打印“第二个是冠军”
  • If third one has the biggest value, I want to print "Third one is champion" 如果第三者具有最大价值,我想打印“第三者是冠军”

Is there an easy way to do this other then creating an if structure - "check aa with bb, aa with cc, bb with cc" 有没有一种简单的方法可以做到这一点,然后创建一个if结构-“用bb检查aa,用cc检查aa,用cc检查bb”

In other words, how to get the variable with biggest left property. 换句话说,如何获得具有最大左属性的变量。

Sure, just do this: 当然,只要这样做:

pseudocode: 伪代码:

let biggest = aa
if (bb.left > biggest.left)
    biggest = bb
if (cc.left > biggest.left)
    biggest = cc

print(biggest.name + " is the champion)

If you have a lot more, then u can use an array 如果还有更多,那么您可以使用数组

ie. 即。

arrayOfBoxes = [aa, bb, cc]
let biggest = arrayOfBoxes[0]
for each box in arrayOfBoxes
    if (box.left > biggest.left)
        biggest = box
print(biggest.name + " is the champion)

Another way you could do it is grab the controls that you care about into a list: 您可以执行的另一种方法是将您关心的控件捕获到列表中:

var horses = Controls.Cast<Control>()
    .Where(c => c.Name == "aa" || c.Name == "bb" || c.Name == "cc");

If you have a lot of controls that represent horses, it might be easier to give them all some common Tag value, so you can search on just that field: 如果您有很多代表马的控件,给它们提供一些通用的Tag值可能会更容易,因此您可以在该字段上进行搜索:

var horses = Controls.Cast<Control>().Where(c => c.Tag.ToString() == "horse");

Then you can find the winning horse by getting the Name of the control (or the Text , or whichever property you store the identifier that the user would understand) whose Left property is the Max : 然后,您可以通过获取其Left属性为Max的控件Name (或Text或存储用户可以理解的标识符的任何属性)来找到获胜的马:

var winner = horses.First(l => l.Left == horses.Max(h => h.Left)).Name;
MessageBox.Show($"The winner is: {winner}!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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