AlphanumComparator.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. thisNumericChunk = Convert.ToInt32(thisChunk.ToString());
  68. thatNumericChunk = Convert.ToInt32(thatChunk.ToString());
  69. if (thisNumericChunk < thatNumericChunk)
  70. {
  71. result = -1;
  72. }
  73. if (thisNumericChunk > thatNumericChunk)
  74. {
  75. result = 1;
  76. }
  77. }
  78. else
  79. {
  80. result = thisChunk.ToString().CompareTo(thatChunk.ToString());
  81. }
  82. if (result != 0)
  83. {
  84. return result;
  85. }
  86. }
  87. return 0;
  88. }
  89. public int Compare(string x, string y)
  90. {
  91. return CompareValues(x, y);
  92. }
  93. }
  94. }