Answer to Question #340829 in C# for SITHEMBELE

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).


1
Expert's answer
2022-05-14T16:39:30-0400
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS