繁体   English   中英

将文本文件中的数据解析为数组

[英]Parsing data from a text file into an array

我有一个包含以下数据的平面文本文件;

 Following are the names and ages in a text file.
26|Rachel
29|Chris
26|Nathan

数据保存在服务器上(例如http://domain.com/info.dat ),我想阅读此文本文件并将其插入数组(年龄和姓名)。 我想忽略第一行(以下是....)。

我已经对代码进行了排序,以使用 webclient 获取数据文件,并使用 streamreader 打开 dat 文件的代码,如下所示;

using (StreamReader sr = new StreamReader(path))
                {
                    while (sr.Peek() >= 0)
                    {
                        string[] channels = Text.Split('|');

                        foreach (string s in channels)
                        {  

                        }
                    }
                }

上述代码的问题在于将其输入到具有正确列的数组中。 谁能给我一些指示?

非常感谢

使用一些 LINQ 的答案怎么样:

var results = from str in File.ReadAllLines(path).Skip(1)
              where !String.IsNullOrEmpty(str)
              let data = str.Split('|')
              where data.Length == 2
              select new Person { Age = Int32.Parse(data[0], NumberStyles.Integer, CultureInfo.CurrentCulture), Name = data[1] };

results现在是IEnumerable<Person> ,您可以对其执行ToListToArray以获取List<Person>Person[] ,或者您可以简单地将结果与foreach循环一起使用。

更新:这是使此功能更具功能所需的Person class。

public class Person
{
   public int Age { get; set; }
   public string Name { get; set; }
}

你可以做这样的事情。 (没有错误检查,您可能想在解析年龄等时检查错误。

class Person
{
  string Name {get;set;}
  int Age {get;set;}
}

List<Person> people = new List<Person>();
string line;
using (StreamReader sr = new StreamReader(path))
{
  sr.ReadLine();
  while ((line == sr.ReadLine()) != null)
  {
    string[] channels = line.Split('|');    
    people.Add(new Person() {Age=int.Parse(channels[0]), Name=channels[1]});       
  }
}

您应该使用 Dictionary 而不是 Array 来存储数据。 示例代码:

FileStream fs = new FileStream("filename");
Dictionary<int,string> dict = new Dictionary<int,string>();
string line = "";
fs.ReadLine(); //skip the first line
while( (line = fs.ReadLine()) != null)
{
    string parts = line.split("|".ToCharArray());
    dict.Add(int.Parse(parts[0]), parts[1]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM