简体   繁体   中英

Sorting Arrays Ascending and Descending order using Array.Sort() and Array.Reverse()

I have an issue to display names in alphabetical order and vice versa. When I use Array.Sort() it displays the last entry in the first place and then does sorting in alphabetical order. any help, suggestion will be highly appreciated. Below is my code:

static void Main(string[] args)
    {
       string [] lastName = new string [100];
       string inValue = "", moreData = "";
       int nameCnt = 0;



       while (moreData != "N")
       {
           lastName[nameCnt] = Convert.ToString(inValue);
           nameCnt++;
           Console.Write("Enter Last Name: ");
           inValue = Console.ReadLine();
           Console.Write("Keep going Y/N? ");
           moreData = Console.ReadLine();
           moreData = moreData.ToUpper();
       }
       Console.WriteLine();
       Console.WriteLine(nameCnt + " Last Name(s) Entered");

        Console.WriteLine();
        Console.WriteLine("Names in Ascending Order\n");


            Array.Sort(lastName);
            foreach (string name in lastName)
            {

                lastName[nameCnt] = Convert.ToString(inValue);
                Console.Write(name);
            }

            Console.WriteLine();
            Console.WriteLine("Names in Ascending Order\n");


            Array.Reverse(lastName);
            foreach (string name in lastName)
            {
                lastName[nameCnt] = Convert.ToString(inValue);
                Console.Write(name);
            }

        Console.ReadLine();
    }

The misconception is that if you enter four last name to Variable nameCnt = 4 in your foreach at position 4 of your arrangement you enter the last entry you stayed in your Variable inValue

     foreach (string name in lastName)
        {
             /* Asign position 4 to array inValue input 
             lastName[nameCnt] = Convert.ToString(inValue); */
            Console.WriteLine(name);
        }

remove that line and order your first while also

    while (moreData != "N")
        {
            Console.Write("Enter Last Name: ");
            inValue = Console.ReadLine();
            lastName[nameCnt] = Convert.ToString(inValue);
            nameCnt++;
            Console.Write("Keep going Y/N? ");
            moreData = Console.ReadLine().ToUpper();
        }

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