2017-09-17 24 views
-1

我試圖操縱在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!!"); 
    } 

感謝所有您的幫助。

+1

有一個在''G''開始無話? – dasblinkenlight

+0

設備列表中有哪些條目? –

+0

如果你有4個項目,並希望他們所有,這是計數<4(0至3) – derloopkat

回答

3

FindIndex在行中返回-1,因爲在列表中沒有以「G」開頭的索引。

看看這個鏈接查看更多細節: MSDN

,而不是你的代碼,你可以使用:

var hi = device.SingleOrDefault(x => x.StartsWith("G")); 

如果沒有匹配,則hi的值爲null

基於從derloopkat評論:

該指數在如果需要4,而不是3

+0

謝謝你的鏈接和例子,我有G在索引中,但我需要添加一個項目索引訪問它們... – Kate

+0

啊好吧..有道理。 ;)但是你應該用安全的方式,我提到過。 –

+0

如果我更改3到4我需要添加5個項目才能訪問4,這實際上是我的問題... – Kate