C#: Implementation of, or alternative to, StrCmpLogicalW in shlwapi.dll

后端 未结 4 1396
一整个雨季
一整个雨季 2020-12-01 17:04

For natural sorting in my application I currently P/Invoke a function called StrCmpLogicalW in shlwapi.dll. I was thinking about trying to run my application under Mono, but

4条回答
  •  情歌与酒
    2020-12-01 17:55

    I just implemented natural string comparison in C#, perhaps someone might find it useful:

    public class NaturalComparer : IComparer
    {
       public int Compare(string x, string y)
       {
          if (x == null && y == null) return 0;
          if (x == null) return -1;
          if (y == null) return 1;
    
          int lx = x.Length, ly = y.Length;
    
          for (int mx = 0, my = 0; mx < lx && my < ly; mx++, my++)
          {
             if (char.IsDigit(x[mx]) && char.IsDigit(y[my]))
             {
                long vx = 0, vy = 0;
    
                for (; mx < lx && char.IsDigit(x[mx]); mx++)
                   vx = vx * 10 + x[mx] - '0';
    
                for (; my < ly && char.IsDigit(y[my]); my++)
                   vy = vy * 10 + y[my] - '0';
    
                if (vx != vy)
                   return vx > vy ? 1 : -1;
             }
    
             if (mx < lx && my < ly && x[mx] != y[my])
                return x[mx] > y[my] ? 1 : -1;
          }
    
          return lx - ly;
       }
    }
    

提交回复
热议问题