Skip to content

Instantly share code, notes, and snippets.

@ProximaB
Created July 7, 2019 20:28
Show Gist options
  • Save ProximaB/a5bfdbbdaa75e8a75520c7bc3c37a499 to your computer and use it in GitHub Desktop.
Save ProximaB/a5bfdbbdaa75e8a75520c7bc3c37a499 to your computer and use it in GitHub Desktop.
public class NaturalSortComparer<T> : IComparer<string>, IDisposable
{
private bool _isAscending;
private Dictionary<string, string[]> _table = new Dictionary<string, string[]>();
public NaturalSortComparer(bool inAscendingOrder = true)
{
this._isAscending = inAscendingOrder;
}
#region IComparer<string> Members
public int Compare(string x, string y)
{
throw new NotImplementedException();
}
#endregion
#region IComparer<string> Members
int IComparer<string>.Compare(string x, string y)
{
if (x == y)
return 0;
string[] x1, y1;
if (!_table.TryGetValue(x, out x1))
{
x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
_table.Add(x, x1);
}
if (!_table.TryGetValue(y, out y1))
{
y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
_table.Add(y, y1);
}
int returnVal;
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
returnVal = PartCompare(x1[i], y1[i]);
return _isAscending ? returnVal : -returnVal;
}
}
if (y1.Length > x1.Length)
{
returnVal = 1;
}
else if (x1.Length > y1.Length)
{
returnVal = -1;
}
else
{
returnVal = 0;
}
return _isAscending ? returnVal : -returnVal;
}
private static int PartCompare(string left, string right)
{
int x, y;
if (!int.TryParse(left, out x))
return left.CompareTo(right);
if (!int.TryParse(right, out y))
return left.CompareTo(right);
return x.CompareTo(y);
}
#endregion
public void Dispose()
{
_table.Clear();
_table = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment