0

I am trying to check on which item i have clicked, i am making a kind of inventory, that if you clicked on 1W, that texture will change to the clicked texture. This is the list i have made. But i can't seem to find a code that works.

this.drivers = new List<Driver>()
                {
                    new Driver(this.game, this, new Vector2 (0, 62), "1W", "Images/Clubs/Drivers/1W", this.inventory),
                    new Driver(this.game, this, new Vector2 (62, 62), "2W", "Images/Clubs/Drivers/2W", this.inventory),
                    new Driver(this.game, this, new Vector2 (124, 62), "3W", "Images/Clubs/Drivers/3W", this.inventory),
                    new Driver(this.game, this, new Vector2 (186, 62), "4W", "Images/Clubs/Drivers/4W", this.inventory),
                    new Driver(this.game, this, new Vector2 (248, 62), "5W", "Images/Clubs/Drivers/5W", this.inventory),
                    new Driver(this.game, this, new Vector2 (310, 62), "6W", "Images/Clubs/Drivers/6W", this.inventory),
                    new Driver(this.game, this, new Vector2 (0, 124), "7W", "Images/Clubs/Drivers/7W", this.inventory)
                };

I know i can find it to check the name with :

If ( name == "1W")
{
   //Do Something
}

but that will mean, if i want to check all 7 i will get 7 if statements, and i have like 3 of this lists, so that will be like 21 if statements.

I know it is possible in 1 sentence per list but i can't remember the code!

I hope someone can help me!

4

2 回答 2

0

只需创建以下selectedindexchanged事件listbox

this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var SelectedObject = this.drivers[listbox1.SelectedIndex];
    //now you can simply use it SelectedObject.Path or SelectedObject.Name or what ever property names you have
}
于 2013-07-21T15:32:19.533 回答
0

尝试使用 LINQ:

this.drivers.Where(d => d.Name == name).ToList().ForEach(delegate(Driver d)
{
    // Do something
});

如果名称是唯一的,这将更容易使用:

var driver = this.drivers.Single(d => d.Name == name);
// Do something with driver

或者,您可以使用循环:

foreach(var d in this.drivers)
{
    if(d.Name == name)
    {
        // Do something
    }
}

如果您的项目将始终是有序"1W","2W",...的,这些将帮助您识别索引:

var index = int.Parse(name[0].ToString()) - 1; // e.g. "3W"[0].ToString() = "3"
var driver = this.drivers[index];
// Do something
于 2013-07-21T15:09:12.503 回答