简体   繁体   中英

Generic Sort for Number or Alphabet in Ascending or Descending Order

How can I sort Generic array which can contain alphabet or numbers only?

Lets say I have a generic list of array that contains numbers only and can be easily sort using

 public void sortAsc(ref T[] obj)

   {
      do
            {
                didSwap = false;
                for (int i = 0; i < obj.Length - 1; i++)
                {
                    if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))
                    {
                        T temp = obj[i + 1];
                        obj[i + 1] = obj[i];
                        obj[i] = temp;
                        didSwap = true;
                    }
                }
            } while (didSwap);

   }

but if array contains string of names and we wants to sort in same way will fail.

due to this

if (Convert.ToInt32(obj[i]) < Convert.ToInt32(obj[i + 1]))

Please let me know if there is a generic method for this or I will have to separate logic for each.

Take a look at the List<T>.Sort() method as this will do what you need.

It solves your problem of having to use Convert.ToInt32 because by default it will use the IComparer implementation of the actual class being used, which both int and string have already for you.

So for strings:

var list = new List<string> { "dd", "aa", "ss" };
list.Sort();

//Output: list = ["aa", "dd", "ss"]

Or for integers:

var list = new List<int> { 1, 13, 5 };

list.Sort();

//Output: list = [1, 5, 13]

If you want to work with custom classes, just make your class implement IComparable or by having the caller to Sort() to provide a function delegate to use. See the first link for more details in the docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM