简体   繁体   English

搜索数组C#时Foreach越界

[英]Foreach going out of bounds while searching through array c#

The purpose of my program is to take a data txt file and edit it, and/or make additions and subtractions to it. 我程序的目的是获取一个数据txt文件并对其进行编辑,和/或对其进行增减。 The text file format is like this: 文本文件格式如下:

Name|Address|Phone|# of people coming|isRSVP

The code I have seems to be doing it's job all the way up until I try to click one of the names within a listbox and it needs to search through the multidimensional array to pull information out and place within a set of textboxes where they can be edited. 我似乎一直在执行的代码一直都起作用,直到我尝试单击列表框中的一个名称,并且它需要搜索多维数组以提取信息并将其放置在一组文本框中 ,编辑。 The problem is that the foreach loop I use gives me an out of bounds exception. 问题是我使用的foreach循环给了我一个超出范围的异常。 I tried to do a step into debug to make sure the data is correct in the array and see the process. 我尝试执行调试步骤,以确保数组中的数据正确并查看过程。 Everything seems to do correctly but for some reason in the conditional statement person[0]==listbox1.selectedIndex isn't returning true even though both are the same as I seen through the step into process. 一切似乎都正确地执行了,但是由于某种原因,条件语句person[0]==listbox1.selectedIndex没有返回true,即使两者都与我在执行过程中看到的相同。 Any help would be greatly appreciated. 任何帮助将不胜感激。 This is my code: 这是我的代码:

StringBuilder newFile = new StringBuilder();
static  string txtList= "guest_list.txt";    
static string[] file = File.ReadAllLines(txtList);    
static int x = file.Count();
string[,] list = new string[x ,5];

public void loadGuestList()
{

    int count2 = 0;
    foreach (string line in file)
    {
        string[] sliced = line.Split('|');
        int count = 0;

        list[count2, count] = sliced[0];
        count++;
        list[count2, count] = sliced[1];
        count++;
        list[count2,count] = sliced[2];
        count++;
        list[count2,count]= sliced[3];
        count++;
        list[count2, count] = sliced[4];
        count++;
        listBox1.Items.Add(list[count2,0]);
        count2++;
    }
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    foreach (string person in list)
    {
        if (  person[0].ToString()==listBox1.SelectedItem.ToString())
        {
            addTxt.Text = char.ToString(person[1]);
            textPhone.Text = char.ToString(person[2]);
            textPeople.Text = char.ToString(person[3]);
            if (person[4] == 'n' )
            {
            }
            else
            {
                chkRSVP.Checked = true;
            }
            break;
        }
    }
}

The problem lies in this line: 问题出在这一行:

foreach (string person in list)

The list is defined as being string[,] which when you for each over will do every element, not just the column of data. 该列表被定义为string[,] ,当您每次遍历时,它将处理每个元素,而不仅仅是数据列。 You really should do something such as: 您确实应该执行以下操作:

for(int index = 0; index <= list.GetUpperBound(0); index++)
{
    string slice1 = list[index, 0];
    string slice2 = list[index, 1];
    ....
}

or switch to using a Dictionary<string, string[]>() . 或切换为使用Dictionary<string, string[]>()

Try to use a "Person" object and override equals(). 尝试使用“ Person”对象并覆盖equals()。 Right now you're trying to put your multidimensional array (list[0]) into a string, it'll give you a unwanted result. 现在,您正在尝试将多维数组(list [0])放入字符串中,这将给您带来不想要的结果。 You should use list[0,0] instead. 您应该改为使用list [0,0]。

In agreement with Adam Gritt, I tested the following code and it seemed to work: 在与Adam Gritt达成一致之后,我测试了以下代码,它似乎可以正常工作:

using System;

namespace so_foreach_bounds
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            //System.Text.StringBuilder newFile = new System.Text.StringBuilder();
            string txtList= "guest_list.txt";    
            string[] file = System.IO.File.ReadAllLines(txtList);    
            int x = file.Length;
            System.Collections.Generic.List<string[]> list = new System.Collections.Generic.List<string[]> ();

            foreach (string line in file)
            {
                string[] sliced = line.Split('|');
                list.Add(sliced);
            }

            foreach (string[] person in list)
            {
                Console.WriteLine (String.Join(", ", person));

                if (person[0] =="Gary")
                {
                    string txtAdd = person[1];
                    string txtPhone = person[2];
                    string txtpeople = person[3];
                    if (person[4] == "n" )
                    {
                    }
                    else
                    {
                        bool has_resvped = true;
                    }
                    break;
                }

            }
        }
    }
}

The issue is how you are iterating over the 2d array. 问题是您如何遍历2d数组。 It is usually a better idea to create a "Person" class, than try to manage it via arrays though. 创建一个“ Person”类通常比尝试通过数组进行管理更好。 Oh yes, and it's usually a good idea to check that a list box item is selected before attempting to use one of its members. 哦,是的,在尝试使用其成员之一之前,最好先检查是否选中了列表框项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM