At the start of class, I like to call roll. I like to go through my list of students in alphabetical order. Where possible, I like to call students by their first names. Of course, if two students have the same first name, I have to also give the last name so they know who I’m calling. Write a program to help me out. Given a class roll, it is going to tell how I should call the names.
Input
Input consists of up to 200 names, one per line, terminated by the end of file. Each line contains a first and a last name for a particular person. First and last names use 1 to 20 letters (a–z), always starting with an uppercase letters first followed by only lowercase letters. No two people will have exactly the same first and last names.
Output
Print the list of names, one per line, sorted by last name. If two or more people have the same last name, order these people by first name. Where the first name is unambiguous, just list the first name. If two people have the same first name, also list their last names to resolve the ambiguity.
| Sample Input 1 | Sample Output 1 |
|---|---|
|
Code |
Code |

Amit MohantyRank #112 · 20K reputationPosted May 17, 2023, 5:15 AM EDT
Check this
using System; using System.Collections.Generic; class Program { static void Main() { List names = new List(); // Read input names until end of file string input; while ((input = Console.ReadLine()) != "") { names.Add(input); } // Sort the names using a custom comparer names.Sort(new NameComparer()); // Print the sorted names foreach (string name in names) { Console.WriteLine(name); } } } class NameComparer : IComparer { public int Compare(string x, string y) { // Split the names into first and last name string[] nameX = x.Split(' '); string[] nameY = y.Split(' '); string lastNameX = nameX[1]; string lastNameY = nameY[1]; // Compare last names int lastNameComparison = lastNameX.CompareTo(lastNameY); if (lastNameComparison != 0) { return lastNameComparison; } string firstNameX = nameX[0]; string firstNameY = nameY[0]; // Compare first names if last names are the same return firstNameX.CompareTo(firstNameY); } }