1

I have a textfile where I think I need to iterate to get all data. This is how the textfile is constructed: From row 1-9 there is information about the company that will recieve the Invoice. The 10'th row show the amount of items. For example if the 10'th row is 2 then the following rows looks like this:

11 Milk "description of first item"
12 4 "quantity of item 1"
13 25 "price"
14 Condoms "description of second item"
15 10 "quantity of item 2"
16 2.5 "price"

What I want to do now is go through the file step by step and then when i am att line 10, in some way iterate through the amount of items, int this case 2, and then create an object of the data in above text file. This is a five step procedure.
Algorithm:

  1. Read the text file step by step

  2. Add every row in a list

  3. increment integer count by 1

  4. Validate if count is equal to 9(the line before the amount of items)

  5. If count is 9 iterate through the data that the row shows, in this case 2.

I fail to establish number 5 in my algorithm. Here is the algorithm interpreted into code:

 fstream = new FileStream(file, FileMode.Open);
            sReader = new StreamReader(fstream);
            invoice = new Invoice();
            List<string> s = new List<string>();
            List<Items> itms = new List<Items>();
            while ((line = sReader.ReadLine()) != null)
            {
                s.Add(line);
            }
            for (int i = 0; i < s.Count; i++)
            {
                count++;
                //Step 4
                if (count == 9)
                {
                  //Step 5. 
                }

And how do I show that there should be two objects, one with the rows 11-13 as parameters(s[11], s[12], s[13]) and the other object with 14-16?

1 Answer 1

1

How about something like this:

var lines = File.ReadAllLines( file );          
// check number of lines here, make sure there are at least nine and
// that the count is a multiple of three
for( int i = 9; i < lines.Length; i += 3 )
{
    string desc = lines[i + 0],
           qty = lines[i + 1],
           price = lines[i + 2];
    // do work here (step 5)
}

There's also fancier ways of doing this, but this should get you started.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.