C#通过姓名查找员工对象
时间: 2023-11-22 19:55:10 浏览: 31
首先,你需要定义一个`Employee`类,包括姓名和其他属性。然后,你需要创建一个`List<Employee>`对象,并向其中添加多个`Employee`对象。最后,你可以通过LINQ查询来查找指定姓名的员工对象。下面是示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 创建员工列表
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { Name = "张三", Age = 25, Department = "销售部" });
employees.Add(new Employee { Name = "李四", Age = 30, Department = "财务部" });
employees.Add(new Employee { Name = "王五", Age = 28, Department = "市场部" });
// 查询员工信息
Console.Write("请输入要查询的员工姓名:");
string name = Console.ReadLine();
var result = employees.Where(e => e.Name == name).FirstOrDefault();
// 显示查询结果
if (result != null)
{
Console.WriteLine("姓名:{0},年龄:{1},部门:{2}", result.Name, result.Age, result.Department);
}
else
{
Console.WriteLine("未找到该员工!");
}
Console.ReadLine();
}
}
```
在上面的示例代码中,我们定义了一个`Employee`类,包括姓名、年龄和部门属性。然后,我们创建了一个`List<Employee>`对象,并向其中添加了三个`Employee`对象。接下来,我们通过`Where`方法和Lambda表达式来查询指定姓名的员工对象。最后,我们根据查询结果来显示员工信息。