工作环境的build.exe要求代码的using namespace 必须按字母顺序排列,今天被一直提示编译错误,浪费了我N久来手动排序,崩溃了,就想写一个小东西来排序using。
其实以前试过List<string>.Sort(),发现结果并不准确。于是今天晚上抽空自己写了一个,写完了才发现,原来之前一直都忘记trim掉using xxxx;最后面那个分号,所以才导致结果不可靠,郁闷ing。
不过写都写了,还是贴出来记载一下吧。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TC1();
}
private static void TC1()
{
string s = @"using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.IO;
using System;
using System.Xml; ";
//List<string> result = SortString(s.Split('\n'));
string[] results = s.Split('\n');
Trim(results);
List<string> result = new List<string>(results);
result.Sort();
foreach (string r in result)
{
Console.WriteLine(r);
}
}
/// <summary>
/// compare s1 and s2
/// </summary>
/// <param name="s1">s1</param>
/// <param name="s2">s2</param>
/// <returns>1 if s1>s2, 0 if s1==s2, -1 otherwise </returns>
private static int Compare(string s1, string s2)
{
if(s1 == s2)
{
return 0;
}
int len = FindTheMostLength(new string[] { s1, s2 });
for (int i = 0; i < len; i++)
{
if (i >= s1.Length)
{
return -1;
}
if (i >= s2.Length)
{
return 1;
}
if (s1[i] > s2[i])
{
return 1;
}
else if (s1[i] < s2[i])
{
return -1;
}
else
{
continue;
}
}
throw new InvalidProgramException("should not be here");
}
private static List<string> SortString(string[] usings)
{
CheckStringArrayParam(usings);
if (usings.Length == 1)
{
return new List<string>(usings);
}
Trim(usings);
// check char one by one
for (int i = 0; i < usings.Length; i++)
{
for (int j = usings.Length - 1; j > i; j--)
{
if (Compare(usings[j - 1], usings[j]) > 0)
{
string temp = usings[j];
usings[j] = usings[j - 1];
usings[j - 1] = temp;
continue;
}
else
{
continue;
}
}
}
List<string> sorted = new List<string>(usings);
return sorted;
}
private static void CheckStringArrayParam(string[] args)
{
if (args == null)
{
throw new ArgumentNullException("usings");
}
if (args.Length == 0)
{
throw new ArgumentException("usings is an empty array");
}
}
private static void Trim(string[] args)
{
CheckStringArrayParam(args);
for (int i = 0; i < args.Length; i++)
{
args[i] = args[i].Trim();
args[i] = args[i].TrimEnd(';');
}
}
private static int FindTheMostLength(string[] args)
{
CheckStringArrayParam(args);
if (args.Length == 1)
{
return args[0].Length;
}
int len = 0;
foreach (string s in args)
{
len = s.Length > len ? s.Length : len;
}
return len;
}
}
}