0

我正在从文本文件中读取行并将它们存储到数组中。我现在需要遍历每个数组位置的项目。我可以遍历文档中的行,但我也需要遍历数组值。

这是我读取文本文件和构建数组的代码:

  public class people
    {
       public  string name;
       public int empid;
       public  string address;

     }

    private void read()
    {


        using (StreamReader sr = new StreamReader(@"E:\test.txt"))
        {
            while (sr.Peek() >= 0) << This loops through the rows in the text doc 
            {
                string str;
                string[] strArray;
                str = sr.ReadLine();

                strArray = str.Split(',');

                people new_people = new people();

                new_people.name = strArray[0];
                new_people.empid = int.Parse(strArray[1]); // << I need to be able to loop through each of
                new_people.address = strArray[2];          // these and add each on to my query string 
                peoples.Add(new_people);

                listBox1.Items.Add(new_people.name + new_people.empid + new_people.address); //< this displays 
                                                                        // the array values     

            }
          }

我需要这样的东西:

   foreach (string foo in new_people.name[0] )
            {

                cmd.Parameters.Add("@1", SqlDbType.VarChar).Value = foo ;

               // then do this for every item in the array for that position 

                cmd.Parameters.Add("@2", SqlDbType.VarChar).Value = (next set of values);
                cmd.Parameters.Add("@3", SqlDbType.VarChar).Value = (next set of values);

                cmd.ExecuteNonQuery();

            }
4

1 回答 1

0

创建自己的构造函数将帮助您创建 Person 类的实例(person 是单数,people 是复数):

public class Person
{
    public string Name;
    public int Empid;
    public string Address;

    public Person(string name, int empid, string address)
    {
        Name = name;
        Empid = empid;
        Address = address;
    }
}

private void read()
{
    using (StreamReader sr = new StreamReader(@"E:\test.txt"))
    {
        while (sr.Peek() >= 0) 
        {
            string str;
            string[] strArray;
            str = sr.ReadLine();
            strArray = str.Split(',');

            Person newPerson = new Person(strArray[0], int.Parse(strArray[1]), strArray[2]);
            people.Add(newPerson);

            listBox1.Items.Add(newPerson.Name + newPerson.Empid + newPerson.Address);
        }
    }

然后,您可以遍历所有名称:

int i = 0;
foreach (Person p in people)
    cmd.Parameters.Add("@" + (i++), SqlDbType.VarChar).Value = p.Name;
cmd.ExecuteNonQuery();
于 2013-05-07T00:17:53.263 回答