2011-12-19 14 views
7

He estado buscando una solución a esto desde hace un tiempo.IComparer para clasificación natural

Cuando puedo ordenar el siguiente mediante una cadena de tipo I tienen una lista de:

10 
10b 
1111 
1164 
1174 
23 
23A 
23B 
23D 
23E 

Realmente quiero la lista sea:

10 
10b 
23 
23A 
23B 
23D 
23E 
1111 
1164 
1174 

Una especie numérica no hace el trabajo, ya sea .

+0

¿Por qué un tipo numérico no hace el trabajo? – lahsrah

+5

eche un vistazo a http://www.codeproject.com/KB/string/NaturalSortComparer.aspx –

+0

@pratapchandra - debería simplemente hacer que su comentario sea una respuesta oficial. – Jagd

Respuesta

4

Si tiene LINQ, puede utilizar OrderBy:

Regex digitPart = new Regex(@"^\d+", RegexOptions.Compiled); 
... 
myList.OrderBy(x => int.Parse(digitPart.Match(x).Value)) 
+3

funcionó para mí, pero tuve que cambiar Integer.Parse a Int32.Parse, y .value debería estar en mayúscula. Sintaxis, meh ... – Jagd

+0

@Jagd: Vaya: P Soy una persona de VB.NET y está 'Entero 'allí. – Ryan

+0

No está claro a partir de la pregunta si el OP quiere una búsqueda natural completa que también ordene "A1", "A2", "Bumblebee" en ese orden. –

3
using System; 
using System.Collections.Generic; 
using System.Text.RegularExpressions; 

public class NumStrCmp : IComparer<string> { 
    public int Compare(string x, string y){ 
     Regex regex = new Regex(@"(?<NumPart>\d+)(?<StrPart>\D*)",RegexOptions.Compiled); 
     var mx = regex.Match(x); 
     var my = regex.Match(y); 
     var ret = int.Parse(mx.Groups["NumPart"].Value).CompareTo(int.Parse(my.Groups["NumPart"].Value)); 
     if(ret != 0) return ret; 
     return mx.Groups["StrPart"].Value.CompareTo(my.Groups["StrPart"].Value); 
    } 
} 

class Sample { 
    static public void Main(){ 
     var data = new List<string>() {"10","10b","1111","1164","1174","23","23A","23B","23D","23E"}; 
     data.Sort(new NumStrCmp()); 
     foreach(var x in data){ 
      Console.WriteLine(x); 
     } 
    } 
} 
Cuestiones relacionadas