Linq - Order by number then letters
我有一个字符串列表,这些字符串包含数字和单词。
我想做的是按数字(数字顺序)后跟单词(字母顺序)对其进行排序
我的列表不包含两者的混合...这里是一个例子
1, 5, 500 , LT, RT, 400 -> LINQ -> 1,
5, 400, 500, LT, RT
这是我所拥有的一个示例,它可以工作,但我想知道是否有更好的编写方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | int results = 0; // Grabs all voltages var voltage = ActiveRecordLinq.AsQueryable<Equipment>() .OrderBy(x => x.Voltage) .Select(x => x.Voltage) .Distinct() .ToList(); // Order by numeric var numberVoltage = voltage .Where( x => int.TryParse(x, out results)) .OrderBy( x => Convert.ToInt32(x)); // Then by alpha var letterVoltage = voltage .Where(x=> !String.IsNullOrEmpty(x)) .Where(x => !int.TryParse(x, out results)) .OrderBy(x => x); return numberVoltage.Union(letterVoltage) |
感谢您的帮助!
鉴于您是在进程中进行的(因为您有一个 ToList 调用)我想我会使用自定义比较器:
1 2 3 4 5 6 7 | return ActiveRecordLinq.AsQueryable<Equipment>() .Select(x => x.Voltage) .Distinct() .AsEnumerable() // Do the rest in-process .Where(x => !string.IsNullOrEmpty(x)) .OrderBy(x => x, new AlphaNumericComparer()) .ToList(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public int Compare(string first, string second) { // For simplicity, let's assume neither is null :) int firstNumber, secondNumber; bool firstIsNumber = int.TryParse(first, out firstNumber); bool secondIsNumber = int.TryParse(second, out secondNumber); if (firstIsNumber) { // If they're both numbers, compare them; otherwise first comes first return secondIsNumber ? firstNumber.CompareTo(secondNumber) : -1; } // If second is a number, that should come first; otherwise compare // as strings return secondIsNumber ? 1 : first.CompareTo(second); } |
你可以在后半部分使用一个巨大的条件:
1 2 3 4 5 6 7 8 9 10 11 12 | public int Compare(string first, string second) { // For simplicity, let's assume neither is null :) int firstNumber, secondNumber; bool firstIsNumber = int.TryParse(first, out firstNumber); bool secondIsNumber = int.TryParse(second, out secondNumber); return firstIsNumber ? secondIsNumber ? firstNumber.CompareTo(secondNumber) : -1; : secondIsNumber ? 1 : first.CompareTo(second); } |
...但在这种情况下,我认为我不会:)
此解决方案尝试为每个值解析一次。
1 2 3 4 5 6 7 8 9 10 | List<string> voltage = new List<string>() {"1","5","500" ,"LT","RT","400" }; List<string> result = voltage .OrderBy(s => { int i = 0; return int.TryParse(s, out i) ? i : int.MaxValue; }) .ThenBy(s => s) .ToList(); |