Solved

C# .net - Read file into array 6 lines at a time.

Posted on 2013-01-29
7
419 Views
Last Modified: 2013-01-29
Hi,

I have a text file with records made up of 6 lines.

I need to read each record of 6 lines into an array. Sort alphabetically on the first record then recreate the file so its in alphabetical order.

Example file:
Lastname Firstname
Two
Three
Four
Five
Six
Smith John
USA
Kentucky
Male
Married
Blue

Open in new window

In the example, there are two records made up of 6 lines each.

Can anyone assist with this logic? I can find examples when the file is in CSV format but this file structure is weird.

Thanks
0
Comment
Question by:mhdi
  • 3
  • 3
7 Comments
 
LVL 9

Expert Comment

by:gt2847c
ID: 38833587
Just a clarification question...  Is this a school/homework related project?
0
 

Author Comment

by:mhdi
ID: 38833596
no :) its a work related question.

I have a text file of employees with over 2,500 records that I need to sort easily when required.
0
 
LVL 9

Assisted Solution

by:gt2847c
gt2847c earned 250 total points
ID: 38833637
If you're looking to do this in C# (an assumption based on the tags)...  I'm not sure I'd use an array for this, as you don't really get a lot of benefit doing it that way, rather, I'd do this:

1.

Create an object representing your record.

2.

Implement  IComparable interface (CompareTo function) which allows you to use the .Sort() function on collections.  CompareTo allows you to define how you want to sort your objects (which fields in what order, etc).  

3.

Create a static method (call it ReadARecord for purposes of this discussion) that takes a Stream or equivalent file source, news up a record object, reads 6 lines from the source and places them in appropriate fields/properties then returns the populated record object.

4.

Create a static method that reads a file (ReadInAFile) and returns an object collection (Enumerable, List, Dictionary, what have you).  
The ReadInAFile method would call the ReadARecord method to handle individual records.

Obviously you could take this and create a bunch of things out of it, but I'm not sure what the end goal is for this.  If you're just looking to fiddle with the file upon occasion, there's a number of other less complicated ways to do this (simple program that reads six lines, turns them into a .CSV file and dump the CSV into Excel or the like).

Let me know what your goal is and I can give you some more directed advice...
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 38833644
If you install MoreLinq form the NuGet package manager, then you could use the following:

using (StreamWriter writer = new StreamWriter("output.txt"))
{
    File.ReadLines("file.txt")
        .Batch(6)
        .OrderBy(batch => batch.First())
        .ForEach(batch => batch.ForEach(line => writer.WriteLine(line)));
}

Open in new window


Note that this approach is highly dependent on your file structure being exact. If any group of 6 lines is really a group of 5 or less (or more) lines, excluding lines that are blank, then this approach would fail.
0
 

Author Comment

by:mhdi
ID: 38833707
Thanks guys, I am learning fast here. I hadnt see NuGet before which is really cool.

I have the application working in .net4.

It would be great if I can get it working in .net 3.5 which I beleive is standard in windows 7?

The only issue is this "File.ReadLines(path)" as ReadLines is not available in net3.5. Is there anything I can change it too?

if (file.ShowDialog() == DialogResult.OK)
            {
                btnInput.Enabled = false;
                btnSort.Enabled = false;
                
                newPath = file.FileName;
                lblOutput.Text = newPath;

                using (StreamWriter writer = new StreamWriter(newPath))
                {
                    File.ReadLines(path)
                        .Batch(6)
                        .OrderBy(batch => batch.First())
                        .ForEach(batch => batch.ForEach(line => writer.WriteLine(line)));
                }

Open in new window

0
 

Author Comment

by:mhdi
ID: 38833728
I've changed "File.ReadLines(path)" to "File.ReadAllLines(path)" which seems to work.
0
 
LVL 9

Expert Comment

by:gt2847c
ID: 38833751
I get to learn something new too, I hadn't seen the MoreLinq (which appears quite cool - thanks kaufmed)..  

On your substitution above:

File.ReadLines(path) returns an IEnumerable<string>,
File.ReadAllLines(path) returns a string[] (which is also behind the scenes an IEnumerable)
so Linq extensions should work just fine.

ReadLines was introduced in 4 and is available through 4.5
ReadAllLines was introduced in 2 and is available through 4.5

Other than the return type, I've never tested them against each other for performance or memory usage, but with the small number of records you mentioned above, it's rather academic.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now