Home  /  Questions  /  Gem



264   99.7
Feb 06, 2010


Sorting Numeric Text

I have found this useful for when I need to sort names that begin with numbers.

var myList = new List<string>();
myList.Add("10 Kings");
myList.Add("1 Queens");
myList.Add("524 3rd");
myList = myList.OrderBy(x=>x.NumAlpha()).Tolist();


public static string NumAlpha(this string s) 
{ 
   if (s.IsNull()) return string.Empty;
   string s2 = Regex.Replace(s.ToString(), @"^[0-9]+", ""); 
   if (s2.Length != s.Length) 
       s = s.Substring(0, s.Length - s2.Length).PadLeft(10, "0"[0]) + s2; 
          
   return s; 
}

 



55   94.7
Feb 22, 2010
public static readonly Regex regex = new Regex(@"^(?<numbers>\d+)(?<residue>.+)$");
public static string NumAlpha(this string s)   
{   
    if (s == null) return null;
    var match = regex.Match(s);   
    if (match.Success)   
        return string.Format("{0,10}{1}", match.Groups["numbers"], match.Groups["residue"]);   
    return s;   
}   

 
 1 comment
 
Thanks! --- Aaron Burton  Feb 26, 2010