iub3rskillz iub3rskillz - 3 months ago 6x
SQL Question

C# - List<> link id to name

I got this application that reads the employee data from the database, only problem the boss of an employee is set in employee_id and not in name, which is what I am looking for.

I got a List filled with all the employees. So I am looking for a way to query it with LINQ through the list to link the employee_id to the Firstname/Lastname.

Example: The employee with the ID 1 is Nancy and her boss is Andrew, but it doesn't say Andrew it says 2. But it should say Andrew

I also added 2 images below to add to my explanation.

Listview of the employees

Reading out the list of employees into the ListView


First, load the employees into some local variable (you'll need it later):

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

Then edit your foreach cycle:

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

Now you can get the name of the boss like this (in foreach cycle):

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

(You need at least C# 6.0 for the ? operator.)