Parsing data from a text file into an array

I have a text file containing the following data:

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

The data is stored on the server (for example, http://domain.com/info.dat ), I would like to read this text file and insert it into the array (age and name). I would ignore the first line (the following -....).

I sorted the code to capture the data file using webclient and the code to open the dat file using streamreader as follows:

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

The problem with the code above is to inject it into an array with the correct columns. Can someone give me some pointers?

Thank you very much

+4
source share
3 answers

What about the answer that some LINQ uses:

 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 now an IEnumerable<Person> , which you can do ToList or ToArray to get a List<Person> or Person[] , or you can just use the results with a foreach .

UPDATE:, here is the Person class needed to make it more functional.

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

You could do something like this. (There is no error checking, you can check for errors when analyzing age, etc.

 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]}); } } 
+1
source

To store data, you should use a dictionary, not an array. Code example:

 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]); } 
0
source

All Articles