请问,在List集合中如何得到元素的索引值
List<TextBox> list = new List<TextBox>{textBox1、textBox2、textBox3、textBox4}
请问,如何得到textBox3在list集合中的索引值。
[解决办法]
你可以
for (int i = 0; i < list.Count; i++)
{
if (list[i] == textBox3) Console.Write(i);
}
[解决办法]
你可以使用FindIndex方法
private void Form1_Load(object sender, EventArgs e) { TextBox textBox1 = new TextBox(); textBox1.Name = "X1"; TextBox textBox2 = new TextBox(); textBox2.Name = "X2"; TextBox textBox3 = new TextBox(); textBox3.Name = "X3"; TextBox textBox4 = new TextBox(); textBox4.Name = "X4"; List<TextBox> list = new List<TextBox> { textBox1, textBox2, textBox3, textBox4 }; int x = list.FindIndex(GetTextBox); MessageBox.Show(x.ToString()); } private static bool GetTextBox(TextBox s) { if (s.Name == "X2") { return true; } else { return false; } }
[解决办法]
List<TextBox> list = new List<TextBox>{textBox1、textBox2、textBox3、textBox4}
int index = list.IndexOf(textBox3,0,0);
[解决办法]
IndexOf貌似是有问题的
list.IndexOf(textBox3,0,0)返回-1
写成
list.IndexOf(textBox3)
即可