Solved

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

Posted on 2013-01-29
7
428 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
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

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

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

Suggested Solutions

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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…

738 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