我試圖操縱在C#中的列表,但我不知道爲什麼我的列表中得到一個錯誤:表計數指數錯誤C#
System.ArgumentOutOfRangeException
這不是邏輯,因爲在位置0指數開始,我有4個項目。
因此對於檢查指標,我使用的計數< 3:
要重現這個bug,這裏是1個文本框和1個按鈕一個簡單的例子:在最後一行
List<string> device = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
// check index
if (device.Count < 3)
{
device.Add(textBox1.Text);
}
else if (device.Count == 3)
{
string ac = device.ElementAt(device.FindIndex(x => x.StartsWith("T")));
string dc = device.ElementAt(device.FindIndex(x => x.StartsWith("E")));
string fg = device.ElementAt(device.FindIndex(x => x.StartsWith("B")));
string hi = device.ElementAt(device.FindIndex(x => x.StartsWith("G"))); // null 'System.ArgumentOutOfRangeException'
MessageBox.Show(ac + "," + dc + "," + fg + " pushed to db table!!");
//Console.WriteLine(ac + "," + dc + "," + fg + " pushed to db table!!");
}
}
,var 嗨得到這個錯誤System.ArgumentOutOfRangeException,你能解釋我的請問我的代碼有什麼問題?
我已經找到了解決辦法,
更新:
List<string> device = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
// check index
device.Add(textBox1.Text);
//textBox1.Clear();
textBox1.Focus();
if (device.Count < 4) return;
string ac = device.ElementAt(device.FindIndex(x => x.StartsWith("T")));
string dc = device.ElementAt(device.FindIndex(x => x.StartsWith("E")));
string fg = device.ElementAt(device.FindIndex(x => x.StartsWith("B")));
string hi = device.ElementAt(device.FindIndex(x => x.StartsWith("G")));
// string hi = device.FirstOrDefault(d => d.StartsWith(("G"))); //is null
MessageBox.Show(ac + "," + dc + "," + fg + ", " + hi + " pushed to db table!!");
//Console.WriteLine(ac + "," + dc + "," + fg + " pushed to db table!!");
}
感謝所有您的幫助。
有一個在''G''開始無話? – dasblinkenlight
設備列表中有哪些條目? –
如果你有4個項目,並希望他們所有,這是計數<4(0至3) – derloopkat