我如何将someting.split()的一部分存储到它自己的数组中?

时间:2019-09-24 21:01:51

标签: c#

我有这段代码读取一个csv文件,并且它在每一行上都使用line.split(',')将一行的每一部分排序为一个字符串数组values

然后如何将“ values [1]”放入其自己的数组中?

static void Main(string[] args)
{
    string line;
    string[] countrys;

    using (StreamReader sr = new StreamReader("Countries_database.csv"))
    {
        try
        {
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine();
                var values = line.Split(',');
                Console.WriteLine(values[1]);
            }
            countrys = values[1];
        }
        catch(Exception ex)
        {
            Console.WriteLine("The file could not be read {0}", ex);
        }

    }
}

countrys = values[1];无效,只是显示了我要做什么。

非常感谢!

2 个答案:

答案 0 :(得分:2)

列表如何?这样,您就不必担心索引编制/大小调整。

List<string> countries = new List<string>();
...//read stuff
countries.Add(values[1]); //add the string to the list

答案 1 :(得分:2)

您的values数组对象不在范围内,无法将其分配给countrys-即您在哪里:

countrys = values[1];

您的var values = line.Split(',');仅在while循环的迭代范围内创建values。因此,理想情况下,应将其添加到while循环外部声明的列表中,或在while循环中分配一次,然后退出while循环。

类似的方法可能会更好:

static void Main(string[] args)
{
    string line;
    List<string> countrys = new List<string>();

    using (StreamReader sr = new StreamReader("Countries_database.csv"))
    {
        try
        {
            while ((line = sr.ReadLine()) != null)
            {
                Console.WriteLine();
                var values = line.Split(',');
                Console.WriteLine(values[1]);
                countrys.Add(values[1]);
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine("The file could not be read {0}", ex);
        }

    }
}