4

I have a flat text file that contains the following data;

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

The data is kept on a server (e.g http://domain.com/info.dat), I'd like to read this text file and insert it into an array (age and name). I'd like to ignore the first line (Following are....).

I've sorted the code to grab the data file using a 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 above code is when it comes to inputting it into an array with the correct columns. Could anyone give me some pointers?

Many thanks

3 Answers 3

5

How about an answer that uses some 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 is now IEnumerable<Person> which you can do ToList or ToArray on to get a List<Person> or Person[], or you can simply use the results with a foreach loop.

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

public class Person
{
   public int Age { get; set; }
   public string Name { get; set; }
}
Sign up to request clarification or add additional context in comments.

17 Comments

FUNKY! But for some reason I like it... even though I can't, for the life of me, understand LINQ... it's THE most impenetrable, unnatural, gowd-awful syntax I've ever encountered (excluding REGEX's, obviously).
Hi thanks for the reply, i'm having issues with this code in that the IDE doesnt like Person. Is there a reference i need for this?
Nathan: Oh. From one of the other answers you mentioned that you wanted to put the data into a Person class. I assumed you already had it at the ready. I'll address that in an update.
@corlettk: I find the LINQ syntax so natural to read. It's like a sentence.
Sorry about that, i was being a bit dumb! i had changed the Person class name. Thank you.
|
1

You could do something like this. (There is no error checking, you might want to check for errors when parsing the 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]});       
  }
}

2 Comments

That's about what I was thinking... Except, why is that people create List's called "array" and arrays called "list"? Just curious ;-)
@corlettk, to be honest I normally would not have called it array, but in this case I did so that the OP could correlate that to the terminology in the question. The OP wanted an array so I am showing by convention where I am addressing that requirement though not with an array, I have a strange mind!!!
0

You should use Dictionary and not Array to store the data. Sample code:

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

2 Comments

Personally, I'd just create a List<Person>; where Person has attributes Name and Age... unless I had a REASON to use some other datastructure, such as a Map... Like for instance I didn't know at compile time what the attributes of Person are... But in this case I do.
Agree, creating a strong type to represent data is also an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.