Link to home
Start Free TrialLog in
Avatar of zhshqzyc
zhshqzyc

asked on

output text file according the column values

Hi, I have a text file.
I want to order the values from small to large by column n, then output to a new file. Hopefully linq code.

Thanks

Avatar of zhshqzyc
zhshqzyc

ASKER

By the way, from the second row.
The first line is a header which is not numeric.
Avatar of kaufmed
Can you provide a sample, real or replicated, of what the data looks like?
P_HWD	P	BP	NMISS	BETA	SE	
4026	38/492/1483	0.7826	0.03842	125456933	1993	
2589      135/770/1068	0.8619	0.6415	21227772	1952
4016	1/105/1902	1	0.7665	1347325	        1987
1234      424/1024/568	0.3705	0.2921	185118462	1995	

Open in new window

For example order by column 5.
I want to order the values from small to large
By text length, or actual (converted) value?
By actual (converted) value.
Your sample data appears to be tab-delimited. If so, then the following should be adequate; if not, then we can modify the split operation accordingly.
string[] lines;
string heading;

using (System.IO.StreamReader reader = new System.IO.StreamReader("input.txt"))
{
    heading = reader.ReadLine();

    var sorted = from line in reader.ReadToEnd().Split('\n')
                 let columns = line.Split('\t')
                 orderby Convert.ToDouble(columns[4])
                 select line;

    lines = sorted.ToArray();
}

using (System.IO.StreamWriter writer = new System.IO.StreamWriter("output.txt"))
{
    writer.WriteLine(heading);
    writer.Write(string.Join("\n", lines));
}

Open in new window

P.S.

As you can see, there is no error checking, so you'll probably want to add some (especially with "Convert.ToDouble()").
If we restrict the value of column 3 within a scope. Can we say
using (System.IO.StreamReader reader = new System.IO.StreamReader("input.txt"))
{
    heading = reader.ReadLine();

    var sorted = from line in reader.ReadToEnd().Split('\n')
                 let columns = line.Split('\t')
                 where(column[3]>1000.00 && column[3]<=5000.00)
                 orderby Convert.ToDouble(columns[4])
                 select line;

    lines = sorted.ToArray();
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks.