Solved

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

Posted on 2013-01-29
7
422 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

790 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