从文本文件中读取数据并将其存储到集合中

我正在尝试读取由制表符 '\t' 分隔的文本并将其存储到对象列表中。文本如下所示:


1   Name    Number      City

我试过这种方法,但它只适用于一行:


string line = sr.ReadLine();

string[] word = line.Split('\t');


for (int i = 0; i <= word.Length; i++)


ec.code = Convert.ToInt32(word[0]);

ec.Name = word[1];

ec.Number = Convert.ToInt32(word[2]);

ec.City = word[3];

list.Add(ec);

如何读取列表中的所有行?


青春有我
浏览 324回答 2
2回答

当年话下

问题很简单,当您执行sr.ReadLine(). 相反,您可以考虑使用File.ReadAllLines,它将所有行读入一个数组。您可以将此与Split方法结合使用,以从每一行中提取您需要的项目。您的 for 循环也没有意义 - 看起来您正在循环行中的每个单词,但在循环的主体中,您每次都添加所有单词。我认为for可以删除循环。此外,不清楚是什么ec,但您可能应该在每次迭代时实例化一个新的。否则,您只是一遍又一遍地向列表添加相同的引用,它们都将具有相同的值(从读取的最后一行开始)。这是我正在使用的示例类:// Class to represent whatever it is you're adding in your loopclass EC{&nbsp; &nbsp; public int Code { get; set; }&nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; public int Number { get; set; }&nbsp; &nbsp; public string City { get; set; }}我们应该做的一件事是,在将索引引用到调用返回的数组之前Split,我们应该先确保有足够的项。否则,IndexOutOfRange如果我们尝试引用一个不存在的索引,我们将得到一个异常。此外,确保我们期望为整数的字符串实际上是整数也是一个好主意。我们可以通过 using 来做到这一点int.TryParse,它会在成功时返回 true 并将 out 参数设置为解析的值。这是一个使用所有这些想法的示例:// Path to our filevar filePath = @"f:\public\temp\temp.txt";// The list of things we want to create from the filevar list = new List<EC>();// Read the file and create a new EC for each lineforeach (var line in File.ReadAllLines(filePath)){&nbsp; &nbsp; string[] words = line.Split('\t');&nbsp; &nbsp; // First make sure we have enough words to create an EC&nbsp; &nbsp; if (words.Length > 3)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // These will hold the integers parsed from our words (if parsing succeeds)&nbsp; &nbsp; &nbsp; &nbsp; int code, number;&nbsp; &nbsp; &nbsp; &nbsp; // Use TryParse for any values we expect to be integers&nbsp; &nbsp; &nbsp; &nbsp; if (int.TryParse(words[0], out code) && int.TryParse(words[3], out number))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.Add(new EC&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Code = code,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name = words[1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Number = number,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; City = words[3]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP