Skip to content

Instantly share code, notes, and snippets.

@bungard
Created September 14, 2018 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bungard/b0ff50ddee4534de5443baff10ecfbe8 to your computer and use it in GitHub Desktop.
Save bungard/b0ff50ddee4534de5443baff10ecfbe8 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Comparer
{
public class SemiNumericComparer : IComparer<string>
{
public int Compare(string s1, string s2)
{
int res = Compare(s1, s2, true);
return res;
}
public int Compare(string s1, string s2, bool toplevel)
{
int localRes = 0;
//Purely Numeric Comparisons
if (IsNumeric(s1) && IsNumeric(s2))
{
if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1;
if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1;
if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0;
}
string[] split1 = s1.Split(' ');
string[] split2 = s2.Split(' ');
//If we're dealing with words...might need to recursively call
if (split1.Length > 1 || split2.Length > 1)
{
if (split1.Length == 1) //only one of these has words, and it must be split2
{
localRes = Compare(s1, split2[0], false);//check s1 against the first word in s2
if (localRes == 0) { return -1; }//If the single word == the first word in the other..then the single wins
else return localRes;
}
if (split2.Length == 1) //only one of these has words, and it must be split1
{
localRes = Compare(split1[0], s2, false);//check s2 against the first word in s1
if (localRes == 0) { return 1; }
else return localRes;
}
//If the first word is the same..lets compare the rest
if (split1[0] == split2[0])
{
List<string> l1 = new List<string>(split1);
l1.RemoveAt(0);
List<string> l2 = new List<string>(split2);
l2.RemoveAt(0);
return Compare(String.Join(" ", l1), string.Join(" ", l2), false);
}
}
if (IsNumeric(s1) && !IsNumeric(s2))
return -1;
if (!IsNumeric(s1) && IsNumeric(s2))
return 1;
return string.Compare(s1, s2, true);
}
public static bool IsNumeric(object value)
{
try
{
int i = Convert.ToInt32(value.ToString());
return true;
}
catch (FormatException)
{
return false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment