C# - 列出<>将ID链接到名称

时间:2016-06-25 21:22:22

标签: c# sql winforms linq listview

我得到了这个从数据库中读取员工数据的应用程序,只有员工的老板设置在employee_id而不是名字中的问题,这就是我正在寻找的。

我得到了一份满是所有员工的名单。所以我正在寻找一种方法,通过列表查询LINQ,将employee_id链接到名字/姓氏。

示例:身份证号为1的员工是南希,她的老板是安德鲁,但它没有说安德鲁说它2.但应该说安德鲁

我还在下面添加了2张图片,以添加到我的解释中。

Listview of the employees

Reading out the list of employees into the ListView

3 个答案:

答案 0 :(得分:1)

所以你需要左加入 IDBoss并获得Boss信息如果找到:

var employees = Database.getEmployees();

var employeesWithBoss = (from e in employees
                        join b in employees
                        on e.ID equals b.Boss into leftJoin
                        from boss in leftJoin.DefaultIfEmpty()
                        select new
                        {
                            Employee = e,
                            BossFirstName = boss == null ? null : boss.FirstName,
                            BossLastName = boss == null ? null : boss.LastName          
                        }).ToList();

foreach (var employee in employeesWithBoss)
{
    // do your normal work here, you now
    // have employee.BossFirstName and employee.BossLastName
}

答案 1 :(得分:1)

首先,将员工加载到一些局部变量中(稍后您将需要它):

List<Employee> employees = Database.getEmployees();

然后编辑您的foreach周期:

// 'employee' is better because here it is really just one specific employee
foreach (Employee employee in employees)

现在你可以像这样得到老板的名字(在foreach循环中):

string boss = employees.FirstOrDefault(x => x.ID == employee.ReportsTo)?.FirstName;

?运算符至少需要C#6.0。)

答案 2 :(得分:0)

你可以使用lambda来实现这一点。

class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>();
        employees.Add(new Employee() { EmployeeName = "Nancy", EmployeeId = 1, BossId = 2 });
        employees.Add(new Employee() { EmployeeName = "Andrew", EmployeeId = 2, BossId = 0 });
        employees.Add(new Employee() { EmployeeName = "Janet", EmployeeId = 1, BossId = 2 });

        var employeesWithBossName = employees.Join(employees,
             emp1 => emp1.BossId,
             emp2 => emp2.EmployeeId,
             (emp1, emp2) => new { EmployeeName = emp1.EmployeeName, BossName = emp2.EmployeeName });

        foreach (var item in employeesWithBossName)
        {
            Console.WriteLine("{0} {1}", item.EmployeeName, item.BossName);
        }
        Console.Read();
    }
}

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int BossId { get; set; }
}

希望这会有所帮助。