智能文件名排序
默認排序問題
windows排序
Windows的資源管理中,提供了文件名的智能排序功能,可以識別出文件名中數(shù)字(數(shù)字位數(shù)不相同),然后比較數(shù)字大小進行排序,如下圖:
代碼默認排序
但在C#中的列表排序中則是按照從左到右一個一個字符進行比較進行排序,如下圖:
List<string> list=new List<string>(); list.Add("文件(11)"); list.Add("文件(22)"); list.Add("文件(1)"); list.Add("文件(2)"); list.Add("文件(3)"); list.Add("文件(4)"); list.Sort(); list.ForEach(l=>Console.WriteLine(l));運行效果
?
排序改進
文件名比較方法
public static int FileNameCompare(string s1, string s2){MatchCollection matchList1 = Regex.Matches(s1, @"\d+");//找出字符串s1中的數(shù)字MatchCollection matchList2 = Regex.Matches(s2, @"\d+");//找出字符串s2中的數(shù)字int minCount = matchList1.Count >= matchList2.Count ? matchList2.Count : matchList1.Count;for (int i = 0; i < minCount; i++){//循環(huán)數(shù)字一一比較if (matchList1[i].Index != matchList2[i].Index)break;//數(shù)字位置不同,直接使用字符串比較if (s1.Substring(0, matchList1[i].Index) != s2.Substring(0, matchList2[i].Index))break;//數(shù)字之前字符不同,直接使用字符串比較if (matchList1[i].Value == matchList2[i].Value)continue;//數(shù)字相同時,比較下一組數(shù)字int s = matchList1[i].Value.Length - matchList2[i].Value.Length;if (s == 0)break;//數(shù)字位數(shù)相同,直接使用字符串比較string temp = "";if (s > 0) //這里不直接比較數(shù)字,是為了對數(shù)字之后的字符串再進行比較 {//當s1的數(shù)字長度大于s2時,對s2的前面進行補0操作,然后在比較s1與s2字符串temp = s2;for (int n = 0; n < s; n++){temp = s2.Insert(matchList2[i].Index, "0");}int r = s1.CompareTo(temp);return r == 0 ? -1 : r;}if (s < 0){//當s1的數(shù)字長度小于s2時,對s1的前面進行補0操作,然后在比較s1與s2字符串temp = s1;for (int n = 0; n < Math.Abs(s); n++){temp = s1.Insert(matchList1[i].Index, "0");}int r = temp.CompareTo(s2);return r == 0 ? 1 : r;}}return s1.CompareTo(s2);}?
方法使用
?
List<string> list = new List<string>();list.Add("文件(11)");list.Add("文件(22)");list.Add("文(11)件(1)");list.Add("文(2)件(2)");list.Add("文件(3)");list.Add("文件(4)");list.Sort((m1, m2) => Common.THMethod.FileNameCompare(m1, m2));list.ForEach(l => Console.WriteLine(l));?
效果
?
?
轉載于:https://www.cnblogs.com/zlulu/p/6214758.html
總結
- 上一篇: 关于冒泡、快排、二分排序算法分析
- 下一篇: HAWQ取代传统数仓实践(一)——为什么