How can I use C# to sort values numerically?

前端 未结 9 1631
醉话见心
醉话见心 2021-02-20 03:20

I have a string that contains numbers separated by periods. When I sort it appears like this since it is a string: (ascii char order)

3.9.5.2.1.1
3.9.5.2.1.10
3.         


        
9条回答
  •  温柔的废话
    2021-02-20 03:36

    Not really, though you may be able to use Regexes or Linq to avoid too much wheel-reinventing. Keep in mind it will cost you much the same computationally to use something built-in as to roll your own.

    Try this:

    List myList = GetNumberStrings();
    
    myList.Select(s=>s.Split('.')).ToArray().
       .Sort((a,b)=>RecursiveCompare(a,b))
       .Select(a=>a.Aggregate(new StringBuilder(),
          (s,sb)=>sb.Append(s).Append(".")).Remove(sb.Length-1, 1).ToString())
       .ToList();
    
    ...
    
    public int RecursiveCompare(string[] a, string[] b)
    {
        return RecursiveCompare(a,b,0)
    }
    
    public int RecursiveCompare(string[] a, string[] b, int index)
    {
        return index == a.Length || index == b.Length 
            ? 0 
            : a[index] < b[index] 
                ? -1 
                : a[index] > b[index] 
                    ? 1 
                    : RecursiveCompare(a,b, index++);
    }
    

    Not the most compact, but it should work and you could use a y-combinator to make the comparison a lambda.

提交回复
热议问题