How to sort elements of array list in C#

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

    If you can be sure the list contains only strings that can be transformed to integers, then with the IEnumerable<T>.OrderBy extension method, try this:

    var sortedList = list.OrderBy(item => int.Parse(item));
    

    If you're using an ArrayList instead of a List<string> (boo!), you'll need to Cast first:

    var sortedList = list.Cast<string>().OrderBy(item => int.Parse(item));
    

    You can also define your own comparer as JaredPar noted, but IMO that's a lot of work for something that's already implemented. However, it's more efficient.

    0 讨论(0)
  • 2021-02-15 00:20
     List<int> liDllCnt = new List<int>();
     for (int temp = 0; temp < alFileName.Count; temp++)
         liDllCnt.Add(Int32.Parse(alFileName[temp].ToString()));
     liDllCnt.Sort();
    

    alFileName is the name of the arraylist that i used.

    0 讨论(0)
  • 2021-02-15 00:28

    Maybe you could store the values in a strongly typed list like List instead, and the, if necessary, convert them to string, when cosuming them. Like this:

            List<int> intList = new List<int>(new int[] {3, 2, 1});
    
            intList.Sort();
    
            foreach (int theInt in intList)
            {
                System.Diagnostics.Debug.WriteLine(theInt.ToString());
            }
    
    0 讨论(0)
提交回复
热议问题