当前正在尝试读取每行的第一个单词
while ((line = studentsReader.ReadLine()) != null)
{
foreach (var lines in line.Split('\n'))
{
arr = line.Split(',');
}
}
尝试过但没用,arr[1]
仍然给我起了名字Oliver
我希望arr[0]
是v12345
,而arr[1]
是v54321
,而不是Oliver
文本文件看起来像这样:
v12345, Oliver, Queen
v54321, Barry, Allen
v51213, Tony, Stark
答案 0 :(得分:3)
您需要将第一个单词添加到新集合中。
var arr = new List<string>();
while ((line = studentsReader.ReadLine()) != null)
{
arr.Add(line.Split(',')[0]);
}
答案 1 :(得分:1)
如果这是文件,则可以
var arr = File.ReadLines(<file name>).Select(l=>l.Split(',')[0]).ToList();
答案 2 :(得分:-1)
对不起。但是您的代码很混乱。
while ((line = studentsReader.ReadLine()) != null)//ReadLine reads only one line from a file, e. g. v12345, Oliver, Queen
{
foreach (var lines in line.Split('\n'))//spiltting than single line by '\n' does nothing
{
/*Now you split by ',' not the iterator, which is lines,
but an original string, which is line.
But because you didn't actually split anything it makes no difference*/
arr = line.Split(',');
/*here you've got an array of strings {v12345, Oliver, Queen}
On next iteration you'll read another line from a file and
get the same array from another string, etc. And on each iteration
the arr will be a new array, so after the last iteration you'll get
the last line of file*/
}
}
您应该执行类似的操作
List<string> firstWords = new List<string>();
while(line = studentsReader.ReadLine()!=null)
{
firstWords.Add(line.Split(',')[0]);
}
答案 3 :(得分:-2)
数组索引从零开始。所以arr [0]会给你第一个单词。