Solved

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

Posted on 2013-01-29
7
417 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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 74

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem with SqlConnection 5 110
comparing string in C# 3 33
Exception in Log4Net 1 18
C# Reverse int in fast ways 6 27
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

708 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

13 Experts available now in Live!

Get 1:1 Help Now