Back to list
Views:   11K
Replies:  1
Archived

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; 
}

 
Aaron Burton, Feb 06, 2010
Reply 1
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;   
}   

 
Pav Lik, Feb 22, 2010


Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas.      Vsn 1.3.0