我正在尝试使用列表来存储和显示数据,从而在控制台应用程序中构建联系人管理器程序。我需要查看显示可用联系人摘要的报告,然后有一个菜单允许用户与该程序进行交互。我有一个方法来创建一个包含数据和联系对象的列表。我创建了一个按名字排序的方法和按姓氏排序的方法,但我不确定如何显示排序回用户的联系人。
任何指导都将不胜感激
static void Main(string[] args)
{
//Declare the list
List<Contact> contactList = new List<Contact>();
//Main Driver
char menuItem;
Console.WriteLine("Contact List\n");
menuItem = GetMenuItem();
while (menuItem != 'Q')
{
ProcessMenuItem(menuItem, contactList);
menuItem = GetMenuItem();
}
Console.WriteLine("\nThank you, goodbye");
Console.ReadLine();
}
//Returns either a 'C', 'R', 'U', 'D', 'L', or 'X' to the caller
static char GetMenuItem()
{
char menuItem;
DisplayMenu();
menuItem = char.ToUpper(IOConsole.GetChar("\nPlease pick an item: "));
while (menuItem != 'C'
&& menuItem != 'R' && menuItem != 'Q' && menuItem != 'U' && menuItem != 'D' && menuItem != 'S' && menuItem != 'L' && menuItem != 'F' && menuItem != 'P' && menuItem != 'T')
{
Console.WriteLine("\nError - Invalid menu item");
DisplayMenu();
menuItem = char.ToUpper(IOConsole.GetChar("\nEnter option or M for menu:"));
}
return menuItem;
}
static void DisplayMenu()
{
Console.WriteLine("C-> Create Contacts");
Console.WriteLine("R-> Remove Contacts");
Console.WriteLine("U-> Update Contacts");
Console.WriteLine("D -> Load data from file");
Console.WriteLine("S-> Save data to file");
Console.WriteLine("L-> View sorted by last name");
Console.WriteLine("F-> View sorted by first name");
Console.WriteLine("P-> View by partial name search");
Console.WriteLine("T-> View by contact type");
Console.WriteLine("Q-> Quit");
}
//Routes to the appropriate process routine based on the user menu choice
static void ProcessMenuItem(Char menuItem, List<Contact> contactList)
{
switch (menuItem)
{
case 'C':
createContact();
break;
case 'R':
removeContact(contactList);
break;
case 'U':
updateContact(contactList);
break;
case 'D':
LoadToFile();
break;
case 'S':
saveToFile();
break;
case 'L':
sortByLastName(contactList);
break;
case 'F':
sortByFirstName(contactList);
break;
case 'P':
DisplayList(contactList);
break;
case 'T':
sortByContactType();
break;
case 'Q':
break;
}
}
//Sorts the list by last name
public static void sortByLastName(List<Contact> contactList )
{
contactList.OrderBy(c => c.GetLastName);
}
//Sorts the list by first name
public static void sortByFirstName(List<Contact> contactList)
{
contactList.OrderBy(c => c.GetFirstName);
}
答案 0 :(得分:0)
为什么不尝试这种方法:
contactList.Sort((x, y) => string.Compare(x.GetLastName, y.GetLastName));