Adrian
Adrian

Reputation: 177

File input and sorting into array for further organization

I am designing a program that will take a file input, in the programs case, a census file that has 4 different inputs age, gender, marital status, and district.

My question's are

  • How exactly could I take the input and sort them into arrays, both integer (age and district) and string (marital status and gender) data types
  • How do I use them to count how many of each there are?

Any suggestions will help! I know how to read in the file and separate the info using input.Split(',') to separate whenever there is a comma, however, I am having trouble looping through so it doesn't repetitively loop unnecessarily.

Upvotes: 0

Views: 54

Answers (1)

Hari Prasad
Hari Prasad

Reputation: 16956

You could do start doing something like this, this code uses Linq.

var records = File.ReadAllLines(filepath) // read all lines
    .Select(line=> line.Split(','))       //  Process each line one by one and split.
    .Select(s=> new                       // Convert to (anonymous)object with properties. 
    {
        Age = int.Parse(s[0]),
        Gender= s[1],
        MaritalStatus,= s[2],  
        Status= s[3],
        District = int.Parse(s[4]),  
    }).ToList();

Now you can access each record using

foreach(var record in records)
{
    // logic
    Console.WriteLine(record);
}

and Count using

int count = records.Count();

Upvotes: 1

Related Questions