Question #340829

Write a program that allows the user to enter any number of names. Your prompt can inform the user to input their first name followed by a space and last name. Order the names in ascending order and display the results with the last name listed first, followed by a comma and then the first name. If a middle initial is entered, it should follow the first name. Your solution should also take into consideration that some users may only enter their last name (one name).


Expert's answer

class Person
        {
            public string[] name { get; set; }


            public Person()
            {
                name = new string[3];
            }
            public override string ToString()
            {
                switch(name.Length)
                {
                    case 1:
                        return $"{name[0]}";
                    case 2:
                        return $"{name[0]},{name[1]}.";
                    case 3:
                        return $"{name[0]},{name[1]} {name[2]}.";
                }
                return null;
            }
        }


        static void Main(string[] args)
        {
            List<Person> people = new List<Person>();
            Console.Write("Enter how many people you want to enter: ");
            int n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                Person person = new Person();
                Console.WriteLine("Input their first name followed by a space and last name.");
                person.name = Console.ReadLine().Split(' ');
                people.Add(person);
            }


            IEnumerable<Person> orderPeople = people.OrderBy(pet => pet.name[0]);


            int j = 1;
            foreach (var person in orderPeople)
            {       
                Console.WriteLine($"{j++} {person}");
            }
            Console.ReadKey();
        }      

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS