Sort String Array As Int

2019-08-01 07:44发布

Is there some way to use IComparer with ArrayList.Sort() to sort a group of strings as ints?

3条回答
在下西门庆
2楼-- · 2019-08-01 08:08

If they are all strings, why are you using an ArrayList? If you're on .Net 2.0 or later, List<string> is a much better choice.

If you're on .Net 3.5 or later:

var result = MyList.OrderBy(o => int.Parse(o.ToString() ) ).ToList();
查看更多
祖国的老花朵
3楼-- · 2019-08-01 08:11

A slight variation based on Joel's solution

string[] strNums = {"111","32","33","545","1","" ,"23",null};
    var nums = strNums.Where( s => 
        {
        int result;
        return !string.IsNullOrEmpty(s) && int.TryParse(s,out result);
        }
    )
    .Select(s => int.Parse(s))
    .OrderBy(n => n);

    foreach(int num in nums)
    {
        Console.WriteLine(num);
    }
查看更多
Rolldiameter
4楼-- · 2019-08-01 08:14

Sure. Just create the appropriate comparer that does the conversion.

public class StringAsIntComparer : IComparer {
  public int Compare(object l, object r) {
    int left = Int32.Parse((string)l);
    int right = Int32.Parse((string)r);
    return left.CompareTo(right);
}
查看更多
登录 后发表回答