调用
1 List<string> data = new List<string>() { 2 "D-001-001-001","A-001-004-001","A-001-002-001", 3 "A-002-001-001", "F-004-001-001", "A-003-001-001", 4 "A-004-001-004","A-041-0401-031","" }; 5 var gf = (from e in data select e).OrderBy(x => x, new AlphaNumericComparer()).ToList();
比较器
1 public class AlphaNumericComparer : IComparer<string> 2 { 3 public int Compare(string first, string second) 4 { 5 int firstNumber, secondNumber;//定义数值类型返回值 6 if (string.IsNullOrEmpty(first)) 7 { 8 return -1; 9 } 10 if (string.IsNullOrEmpty(second)) 11 { 12 return -1; 13 } 14 //分割字符串 15 string[] firstArray = first.Split(‘-‘); 16 string[] secondArray = second.Split(‘-‘); 17 List<int> intArray = new List<int>(); 18 //记录比较结果 19 for (int i = 0; i < firstArray.Length; i++) 20 { 21 bool firstIsNumber = int.TryParse(firstArray[i], out firstNumber); 22 bool secondIsNumber = int.TryParse(secondArray[i], out secondNumber); 23 if (firstIsNumber && secondIsNumber) 24 { 25 //数字比较 26 intArray.Add(firstNumber.CompareTo(secondNumber)); 27 } 28 else { 29 //文本比较 30 intArray.Add(firstArray[i].CompareTo(secondArray[i])); 31 } 32 } 33 intArray.Reverse();//从末位开始计算差值 34 int val = 0; 35 //获取差值占比 36 for (int i = 0; i < intArray.Count; i++) 37 { 38 val += intArray[i] * (i+1) * 10; 39 } 40 return val; 41 } 42 }
效果图:
时间: 2024-10-04 00:03:01