• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 872
  • Last Modified:

Sort TSV file in C#

How can I sort a TSV file?
0
wipnav
Asked:
wipnav
  • 2
  • 2
1 Solution
 
Roshan DavisCommented:
something like this?
string [] strVals;
using( StreamReader rdr = new StreamReader( @"c:\a.tsv" ) )
{
	string strTsv, line;
	strTsv = string.Empty;
	
	while( (line = rdr.ReadLine()) != null )
	{
		strTsv += line + '\t';
	}
	strTsv = strTsv.Trim('\t');

	strVals = strTsv.Split('\t');
	
	for(int i = 0 ; i < strVals.Length - 1 ; i ++)
	{
		for(int j = i + 1 ; j < strVals.Length; j ++)
		{
			if(strVals[i].CompareTo(strVals[j]) > 0 )
			{
				string tmp = strVals[i];
				strVals[i] = strVals[j];
				strVals[j] = tmp;
			}
		}
	}
}

if(strVals.Length > 0 )
{
	using( StreamWriter wtr = new StreamWriter(@"c:\a.tsv", false, System.Text.Encoding.ASCII ) )
	{
		foreach(string str in strVals)
		{
			wtr.Write(str + "\t");
		}
	}
}

Open in new window

0
 
wipnavAuthor Commented:
Thanks, that works perfectly, but is there a way to sort it by a column other than the first?
0
 
Roshan DavisCommented:
in that case you may need to make a structure and parse each line into that and add that struct in to an array (here it is strVals). and you can use rest all the logic from the above sample
0
 
wipnavAuthor Commented:
Ok, thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now