Sort String Array As Int

江枫思渺然 提交于 2019-12-11 10:11:58

问题


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


回答1:


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();



回答2:


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);
}



回答3:


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);
    }


来源:https://stackoverflow.com/questions/1179024/sort-string-array-as-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!