前面提到的C#开发的工具中需要实现从大量的文件中,读取到一定结构的字符串,这些字符串有个特征,就是类似英语字符+数字,前后顺序不变。在用了正则表达式完成上述功能之后,为了方便起见,又想对这些字符串进行排序。刚一开始当然是想到了数据结构上学到的那些…………,但是本人比较懒。想起ACM练习的时候,C语言中能调用库函数直接进行排序,那么C#这个后来的功能强大的语言应该也有吧。还真被我在微软的API上给找到了。
直接上代码吧:
private static int CompareDinosByLength(string x, string y){ return x.compareto(b); } list.sort(CompareDinosByLength);
就几行代码直接可以调用很强大的库函数进行排序,感觉真的很不错。在以编写工具提升自己工作效率为目的的情况下,用一点代码完成很强大的功能,而且性能也不差……
附微软的代码:
using System; using System.Collections.Generic; public class Example { private static int CompareDinosByLength(string x, string y) { if (x == null) { if (y == null) { // If x is null and y is null, they're // equal. return 0; } else { // If x is null and y is not null, y // is greater. return -1; } } else { // If x is not null... // if (y == null) // ...and y is null, x is greater. { return 1; } else { // ...and y is not null, compare the // lengths of the two strings. // int retval = x.Length.CompareTo(y.Length); if (retval != 0) { // If the strings are not of equal length, // the longer string is greater. // return retval; } else { // If the strings are of equal length, // sort them with ordinary string comparison. // return x.CompareTo(y); } } } } public static void Main() { List<string> dinosaurs = new List<string>(); dinosaurs.Add("Pachycephalosaurus"); dinosaurs.Add("Amargasaurus"); dinosaurs.Add(""); dinosaurs.Add(null); dinosaurs.Add("Mamenchisaurus"); dinosaurs.Add("Deinonychus"); Display(dinosaurs); Console.WriteLine("\nSort with generic Comparison<string> delegate:"); dinosaurs.Sort(CompareDinosByLength); Display(dinosaurs); } private static void Display(List<string> list) { Console.WriteLine(); foreach( string s in list ) { if (s == null) Console.WriteLine("(null)"); else Console.WriteLine("\"{0}\"", s); } } } /* This code example produces the following output: "Pachycephalosaurus" "Amargasaurus" "" (null) "Mamenchisaurus" "Deinonychus" Sort with generic Comparison<string> delegate: (null) "" "Deinonychus" "Amargasaurus" "Mamenchisaurus" "Pachycephalosaurus" */