拆分数组并在while循环中添加到新数组

时间:2015-04-06 18:48:23

标签: c#

我有一个平面文件,我在C#中读取然后尝试解析。我的意思是将帐号存储在数组中的平面文件中。

 AccountNumber | AccountName | DateCreated 
 1             | Bob         | 1/1/2011    
 2             | Donna       | 3/2/2013    
 3             | Jake        | 2/21/2010   
 5             | Sally       | 4/2/2014    

到目前为止,这就是我的分裂:

//List<string[]> myArrayList = new List<string[]>();
 using (StreamReader read = new StreamReader(@"C:\text\Accounts.txt"))
             {
                 string line;
                 while ((line = read.ReadLine()) != null)
                 {
                     string[] parts = line.Split('|');
                     Console.WriteLine(parts[0]);
                     //myArrayList.Add(parts[0]);
                 }
             }

如何将部分[0]中打印的所有内容存储在while循环之外的自己的数组中?我尝试过添加列表但是我一直在为无效参数收到错误。我评论了那些不起作用的东西。

2 个答案:

答案 0 :(得分:1)

以下代码读取文件内容,拆分行,将其存储在列表中,最后显示RichTextBox中的第一列

private void button1_Click(object sender, EventArgs e)
    {
        List<string[]> myArrayList = new List<string[]>();
        StreamReader read = new StreamReader(@"C:\test\Accounts.txt");

        string line;
        while ((line = read.ReadLine()) != null)
        {
            string[] parts = line.Split('|');
            //Console.WriteLine(parts[0]);
            myArrayList.Add(parts);
        }

        foreach (var account in myArrayList)
        {
            richTextBox1.Text = richTextBox1.Text + account[0].ToString() + Environment.NewLine;
        }
    }

enter image description here

答案 1 :(得分:0)

我喜欢MethodMan的建议:

// Class structure
public class Account
{
    public int AccountNumber;
    public string AccountName;
    public DateTime DateCreated;

    public Account(string[] info)
    {
        // This is all dependent that info passed in, is already valid data.  
        // Otherwise you need to validate it before assigning it
        AccountNumber = Convert.ToInt32(info[0]);
        AccountName = info[1];
        DateCrated = DateTime.Parse(info[2]);
    }
}

使用类结构的代码:

List<Account> myAccounts = new List<Account>();
using (StreamReader read = new StreamReader(@"C:\text\Accounts.txt"))
{
    string line;
    while ((line = read.ReadLine()) != null)
    {
        string[] parts = line.Split('|');
        myAccounts.Add(new Account(parts));
    }
}

// Do whatever you want after you have the list filled