How to sort elements of array list in C#

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

    If you can get the ArrayList items into a strongly typed container such as List or String[] then Linq makes it easy to do the rest. The following implementation parses the string values only once and creates an anonymous type for each with the original string and its integer value.

    public void Test_SortArrayList()
    {
        ArrayList items = new ArrayList(new []{"1", "10", "2", "15", "17", "5", "6", "27", "8", "9"});
        string[] strings = (string[])items.ToArray(typeof(string));
        List result = strings
            .Select(x => new
                {
                    Original = x,
                    Value = Int32.Parse(x)
                })
            .OrderBy(x => x.Value)
            .Select(x => x.Original)
            .ToList();
        result.ForEach(Console.WriteLine);
    }
    

提交回复
热议问题