1

我想在我的代码中实现http://www.davekoelle.com/alphanum.html以对开头和结尾带有数字的字符串进行一些自然排序。我的问题是,没有做太多排序是如何将它实现到我的对象结构中。

我有一个

    List<string[]> myStringArrays = new List<string[]>();

我添加了 1000 个这种类型的数组:

    "text", "text", "1, label:3", "","","", etc ...
    "text", "text", "2, label:2", "","","", etc ...
    "text", "text", "2, label:1", "","","", etc ...
    "text", "text", "10, label:3", "","","", etc ...

编辑:(在本例中标签始终为“标签”)

我一直在用 LINQ 排序

      myStringArrays = myStringArrays.OrderBy(m => m[2]).ToList();

但正如您猜到的那样,它排序给 alpha 排序“1...”、“10...”等等。

我尝试了这种方法:

      myStringArrays = myStringArrays.OrderBy(m => (m[2].Split(',')[0])).ThenBy(m => m[2].Split(':')[2]).ToList();

如果我的第三个字符串不符合该特定格式,则该方法有效但失败。这让我(最终)想到了我的问题——我将如何实现 Alphanum.cs 来解决这个问题?

4

2 回答 2

1

实现起来并不难,只需要解析字符串,将它们分成数字和非数字字符,然后进行比较。这是我放在一起的一个实现:

public class AlphaNum : IComparable<AlphaNum> {

  private List<string> _alphas;
  private List<int> _nums;

  public AlphaNum(string value) {
    _alphas = new List<string>();
    _nums = new List<int>();
    bool alpha = true;
    int ofs = 0;
    for (int i = 0; i <= value.Length; i++) {
      if (i == value.Length || Char.IsDigit(value[i]) == alpha) {
        string s = value.Substring(ofs, i - ofs);
        if (alpha) {
          _alphas.Add(s);
        } else {
          _nums.Add(Int32.Parse(s));
        }
        ofs = i;
        alpha = !alpha;
      }
    }
  }

  public int CompareTo(AlphaNum other) {
    for (int i = 0;; i++) {
      bool e = i >= _alphas.Count;
      bool oe = i >= other._alphas.Count;
      if (e || oe) return e && oe ? 0 : e ? -1 : 1;
      int c = _alphas[i].CompareTo(other._alphas[i]);
      if (c != 0) return c;
      e = i >= _nums.Count;
      oe = i >= other._nums.Count;
      if (e || oe) return e && oe ? 0 : e ? -1 : 1;
      c = _nums[i].CompareTo(other._nums[i]);
      if (c != 0) return c;
    }
  }

}

用法:

myStringArrays = myStringArrays.OrderBy(x => new AlphaNum(x[2])).ToList();
于 2013-01-13T06:56:59.413 回答
0

自然排序的这种实现应该让你开始: http: //www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting

于 2013-01-13T06:24:43.797 回答