我有一个c#项目,我创建了一个名为Employees的类。在这堂课里面,我有了新的名单:
如何显示由我创建的列表的整个数据库?
我怎么才能显示名字?
现在,如果我输入Football
,则只会显示参与Football
的员工姓名
以下是完整的课程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Employee
{
public string employeeID;
public string Name;
public string eventHeld;
public int eventId;
public Employee(string eID, string eName, string eEvents, int eId)
{
this.employeeID = eID;
this.Name = eName;
this.eventHeld = eEvents;
this.eventId = eId;
}
public static void PrintDataBase()
{
}
static void Main()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee("PALI_e1","Parvez Ali","FOOTBALL",1));
employees.Add(new Employee("AALI_e2", "Ashik Ali", "FOOTBALL", 1));
employees.Add(new Employee("AALI_e3", "Aftab Ali", "CHESS", 2));
employees.Add(new Employee("AALI_e4", "Arif Ali", "CRICKET", 3));
Menu.MenuPrinting();
Console.WriteLine("\nPlease Enter Your Choice");
string Choice = Console.ReadLine();
foreach(Employee e in employees)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
}
public class Menu
{
public static void MenuPrinting()
{
Console.WriteLine("Main Menu");
Console.WriteLine("=========");
Console.WriteLine("1. DataBase");
Console.WriteLine("2. Events Held");
Console.WriteLine("3. Name of Emplyee");
}
}
答案 0 :(得分:8)
您可以使用Enumerable.Where
方法根据字段过滤您的收藏:
string Choice = Console.ReadLine();
if(!string.IsNullOrEmpty(Choice))
{
var filteredEmployees = employees.Where(e => e.eventHeld == Choice);
foreach(Employee e in filteredEmployees)
{
Console.WriteLine(e);
}
}
顺便说一句,您需要覆盖ToString
课程的Employee
方法,否则您只会在Console
中看到您的班级名称。此示例应该让您了解如何操作您根据特定字段过滤集合,可以将此逻辑应用于其他属性。
答案 1 :(得分:1)
foreach(Employee e in filteredEmployees)
{
Console.WriteLine(e);
}
否则它将输出e
的数据类型。我想你的意思是
Console.WriteLine(e.employeeID + " " + e.Name + " " + e.eventID + " " + e.eventHeld);
或某些类似于
的输出