Default Scheduling
Sort windows
Windows Explorer, the sorting function provides intelligent file name, can identify the file name in digital ( number of digits are not the same ), and then compare the size of numbers to sort, as follows:
Code default sort
However, the list is sorted in C # in the left to right is a sort of a character comparison, as shown below:
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));
running result
Sort improvement
File Name comparison method
public static int FileNameCompare ( String s1, String S2) { the MatchCollection matchList1 = Regex.Matches (s1, @ " \ + D " ); // find the number in the string s1 the MatchCollection matchList2 = Regex.Matches (S2, @ " \ + D " ); // find the number string s2 int minCount matchList1.Count => = matchList2.Count? matchList2.Count: matchList1.Count; for ( int I = 0 ; I <minCount; I ++ ) { //Digital-one comparison cycle IF (matchList1 [I] = .Index! MatchList2 [I] .Index) BREAK ; // different position numbers, direct string comparison IF (s1.Substring ( 0 , matchList1 [I] .Index) ! s2.Substring = ( 0 , matchList2 [I] .Index)) BREAK ; // before the number of different characters, a direct string comparison IF (matchList1 [I] == .Value matchList2 [I] .Value) Continue ; / / figures are the same, comparing the next set of numbers int S = matchList1 [I] .Value.Length - matchList2 [I] .Value.Length; IF (S == 0 ) BREAK ; // the same number of digits, a direct string comparison String TEMP = "" ; IF (S> 0 ) // where direct comparison is not digital, then to a digital string then compared { // when s1 when the number length is greater than s2, s2 is the complement of the foregoing operation 0, then s1 and s2 in the comparison string TEMP = s2; for ( int n-= 0 ; n-<S; n-++ ) { TEMP = s2.Insert (matchList2 [ I] .Index, " 0 " ); } int R & lt =s1.CompareTo (TEMP); return R & lt == 0 -? . 1 : R & lt; } IF (S < 0 ) { // when the number is less than the length s1 s2, s1 is the complement of the foregoing operation 0, and then compare s1 s2 string with TEMP = S1; for ( int n-= 0 ; n-<the Math.Abs (S); n-++ ) { TEMP = s1.Insert (matchList1 [I] .Index, " 0 " ); } int R & lt = TEMP .CompareTo (s2); return r == 0 ? 1 : r; } } return s1.CompareTo(s2); }
Method uses
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));
effect