将一些字符串,如: "bc", "ad", "ac", "hello", "xman", "little", "during","day"
排序的结果:“ad”,"ac",“bc”,“during”,“day”,“hello”,“little”,“xman”
采用框架自带的排序函数来调用自定义的Compare方法实现,代码段如下所示:
class Program { static void Main(string[] args) { string[] strArr = new string[] { "bc", "ad", "ac", "hello", "xman", "little", "during", "day"}; List<string> strs = new List<string>(); list.AddRange(strArr); /* * Sort string by asc * result : “ad”,"ac",“bc”,“during”,“day”,“hello”,“little”,“xman” */ list.Sort(new CompStr()); foreach (string str in strs) { Console.WriteLine(str); } Console.WriteLine("------------"); //Sort string by desc list.Sort(new CompStrDesc()); foreach (string str in strs) { Console.WriteLine(str); } Console.ReadLine(); } } public class CompStr : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { if (x.Length > 0 && y.Length > 0) { if (x[0].CompareTo(y[0]) == 0) { return -x.CompareTo(y); } } return x.CompareTo(y); } #endregion } public class CompStrDesc : IComparer<string> { #region IComparer<string> Members public int Compare(string x, string y) { if (x.Length > 0 && y.Length > 0) { if (x[0].CompareTo(y[0]) == 0) { return x.CompareTo(y); } } return -x.CompareTo(y); } #endregion }
时间: 2024-10-06 05:19:15