How to sort elements of array list in C#

后端 未结 9 1091
梦如初夏
梦如初夏 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:13

    Implement custom comparer and pass it to ArrayList.Sort()

    Complete Code:

    using System;
    using System.Collections;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                ArrayList a = new ArrayList();
                a.Add("1");
                a.Add("13");
                a.Add("3");
                a.Add("25");
                a.Add("2");
                a.Add("12");
                a.Sort(new CustomComparer());
    
                foreach (String s in a)
                    Console.WriteLine(s);
    
                Console.Read();
            }
    
    
        }
    
        public class CustomComparer : IComparer
        {
            Comparer _comparer = new Comparer(System.Globalization.CultureInfo.CurrentCulture);
    
            public int Compare(object x, object y)
            {
                // Convert string comparisons to int
                return _comparer.Compare(Convert.ToInt32(x), Convert.ToInt32(y));
            }
        }
    }
    

    Output:

    1 2 3 12 13 25

提交回复
热议问题