C#index超出范围String Array和List <string> </string>

时间:2010-12-18 06:47:02

标签: c# arrays

在尝试了一些错误检查方法后,我得出结论,我需要帮助解决这个问题。

我怎么没有发现这个“索引超出范围”错误。在未来的良好实践中,我该怎么做才能避免这个问题?

    public void loadFromFile()
    {
        OpenFileDialog oFile = new OpenFileDialog();
        oFile.Title = "Open text file";
        oFile.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        oFile.FilterIndex = 1;
        oFile.InitialDirectory = Application.StartupPath;
        oFile.AddExtension = true;
        oFile.CheckFileExists = true;
        oFile.CheckPathExists = true;

        // Open and clean Duplicates
        String[] lines;
        List<string> temp = new List<string>();
        List<string> newlist = new List<string>();

        if(oFile.ShowDialog() == DialogResult.OK)
        {
            // Dummy file has 6 lines of text. Filename:DuplicatFile.txt
            // 3 duplicate lines and 3 not.
            lines = File.ReadAllLines(oFile.FileName, System.Text.Encoding.UTF8);

            // Copy array to temporary array
            for (int index=0; index < lines.Length; index++)
            {
                // System.ArgumentOutOfRangeException was unhandled
                // Index was out of range. Must be non-negative and less than the size of the collection.
                if (lines[index].Length >= 0)
                {
                    temp[index] = lines[index];
                }
            }
            // Check for duplicates. If duplicate ignore if non-duplicate add to list.
            foreach (string line in temp)
            {
                if (!newlist.Contains(line))
                {
                    newlist.Add(line);
                }
            }
            // Clear listbox and add new list to listbox.
            lstBox.Items.Clear();
            foreach (string strNewLine in newlist)
            {
                lstBox.Items.Add(strNewLine);
            }
        }
    }

4 个答案:

答案 0 :(得分:8)

List<string> temp = new List<string>();
...
temp[index] = lines[index];

temp从0开始。任何指数都超出范围。

您可以使用temp.Add解决此问题,以使列表动态增长:

temp.Add(lines[index]);

答案 1 :(得分:2)

Mud具有ArgumentOutOfRangeException的正确答案。您可以使用Linq将if语句中的所有代码简化为以下内容:

lines = File.ReadAllLines(oFile.FileName, System.Text.Encoding.UTF8);    
lstBox.Items.AddRange(lines.Distinct().ToArray());

答案 2 :(得分:1)

问题不在于“行”索引超出范围 - 而是“临时”索引超出范围......您创建了一个名为“temp”的新列表,但其中没有任何内容。它的长度是0!

您应该使用.Add方法:

,而不是从一个索引复制到另一个索引
temp.Add(lines[index])

当然......有更好的方法来复制数组,但这最接近你上面提到的并直接回答你的问题。

答案 3 :(得分:1)

您收到该错误,因为列表temp中该索引处没有元素。 (temp为空)。您可以使用temp.Add(value)填写它。

创建临时列表的另一种方法是使用temp = newlist.ToList()

我建议使用LINQ:你可以使用

lstBox.Items.Clear();
foreach (var line in lines.Distinct())
    lstBox.Items.Add(line);

而不是所有这些代码:

// Copy array to temporary array
for (int index=0; index < lines.Length; index++)
{
    // System.ArgumentOutOfRangeException was unhandled
    // Index was out of range. Must be non-negative and less than the size of the collection.
    if (lines[index].Length >= 0)
    {
        temp[index] = lines[index];
    }
 }
 // Check for duplicates. If duplicate ignore if non-duplicate add to list.
 foreach (string line in temp)
 {
   if (!newlist.Contains(line))
   {
       newlist.Add(line);
   }
 }
 lstBox.Items.Clear();
 foreach (string strNewLine in newlist)
 {
    lstBox.Items.Add(strNewLine);
 }

简单: