C#如何查找列表中单击的项目

本文关键字:列表 单击 项目 查找 何查找 | 更新日期: 2023-09-27 18:24:02

我正在检查我点击了哪个项目,我正在进行一种盘点,如果你点击了1W,该纹理将变为点击的纹理。这是我列出的清单。但我似乎找不到一个有效的代码。

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)
                };

我知道我可以找到它来检查名称:

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

但这意味着,如果我想检查所有7个,我会得到7个if语句,我有3个列表,所以这将是21个if语句。

我知道每个列表一句话就可以实现,但我记不清代码了!

我希望有人能帮助我!

C#如何查找列表中单击的项目

尝试使用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

只需创建listbox:的selectedindexchanged事件

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
}