AlphanumComparator.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace MediaBrowser.Server.Implementations.Sorting
  5. {
  6. public class AlphanumComparator : IComparer<string>
  7. {
  8. private enum ChunkType { Alphanumeric, Numeric };
  9. private static bool InChunk(char ch, char otherCh)
  10. {
  11. var type = ChunkType.Alphanumeric;
  12. if (char.IsDigit(otherCh))
  13. {
  14. type = ChunkType.Numeric;
  15. }
  16. if ((type == ChunkType.Alphanumeric && char.IsDigit(ch))
  17. || (type == ChunkType.Numeric && !char.IsDigit(ch)))
  18. {
  19. return false;
  20. }
  21. return true;
  22. }
  23. public static int CompareValues(string s1, string s2)
  24. {
  25. if (s1 == null || s2 == null)
  26. {
  27. return 0;
  28. }
  29. int thisMarker = 0, thisNumericChunk = 0;
  30. int thatMarker = 0, thatNumericChunk = 0;
  31. while ((thisMarker < s1.Length) || (thatMarker < s2.Length))
  32. {
  33. if (thisMarker >= s1.Length)
  34. {
  35. return -1;
  36. }
  37. else if (thatMarker >= s2.Length)
  38. {
  39. return 1;
  40. }
  41. char thisCh = s1[thisMarker];
  42. char thatCh = s2[thatMarker];
  43. StringBuilder thisChunk = new StringBuilder();
  44. StringBuilder thatChunk = new StringBuilder();
  45. while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || InChunk(thisCh, thisChunk[0])))
  46. {
  47. thisChunk.Append(thisCh);
  48. thisMarker++;
  49. if (thisMarker < s1.Length)
  50. {
  51. thisCh = s1[thisMarker];
  52. }
  53. }
  54. while ((thatMarker < s2.Length) && (thatChunk.Length == 0 || InChunk(thatCh, thatChunk[0])))
  55. {
  56. thatChunk.Append(thatCh);
  57. thatMarker++;
  58. if (thatMarker < s2.Length)
  59. {
  60. thatCh = s2[thatMarker];
  61. }
  62. }
  63. int result = 0;
  64. // If both chunks contain numeric characters, sort them numerically
  65. if (char.IsDigit(thisChunk[0]) && char.IsDigit(thatChunk[0]))
  66. {
  67. if (!int.TryParse(thisChunk.ToString(), out thisNumericChunk))
  68. {
  69. return 0;
  70. }
  71. if (!int.TryParse(thatChunk.ToString(), out thatNumericChunk))
  72. {
  73. return 0;
  74. }
  75. if (thisNumericChunk < thatNumericChunk)
  76. {
  77. result = -1;
  78. }
  79. if (thisNumericChunk > thatNumericChunk)
  80. {
  81. result = 1;
  82. }
  83. }
  84. else
  85. {
  86. result = thisChunk.ToString().CompareTo(thatChunk.ToString());
  87. }
  88. if (result != 0)
  89. {
  90. return result;
  91. }
  92. }
  93. return 0;
  94. }
  95. public int Compare(string x, string y)
  96. {
  97. return CompareValues(x, y);
  98. }
  99. }
  100. }