How to sort elements of array list in C#

后端 未结 9 1085
梦如初夏
梦如初夏 2021-02-14 23:42

I have an ArrayList that contains,

[0] = \"1\"
[1] = \"10\"
[2] = \"2\"
[3] = \"15\"
[4] = \"17\"
[5] = \"5\"
[6] = \"6\"
[7] = \"27\"
[8] = \"8\"
[9] = \"9\"
         


        
9条回答
  •  北海茫月
    2021-02-15 00:12

    This is the safest way

    aryList is your ArrayList instance

                    object[] list = aryList.ToArray();
                    Array.Sort
                        (
                            list,
                            delegate(object x, object y)
                            {
                                int a = 0, b = 0;
                                if (x == y) return 0;
                                if (x == null || y == null)
                                    return x == null ? -1 : 1;
                                int.TryParse(x.ToString(), out a);
                                int.TryParse(y.ToString(), out b);
                                return a.CompareTo(b);
                            }
                        );
    
    
    

    result saved into "list" object array

    提交回复
    热议问题