Skip to content

Instantly share code, notes, and snippets.

@iqan
Created September 25, 2020 16:44
Show Gist options
  • Save iqan/ac5a15eac76c76e44b7711d62b02e072 to your computer and use it in GitHub Desktop.
Save iqan/ac5a15eac76c76e44b7711d62b02e072 to your computer and use it in GitHub Desktop.
Employee Relationship LINQ
using System;
using System.Collections.Generic;
using System.Linq;
namespace employee_ex
{
class Program
{
static void Main(string[] args)
{
var empList = Employee.GetTestData();
var heads = empList.Where(e => e.managerid == null);
var managers = empList.Where(e => e.managerid != null && heads.Any(h => h.employeeid == e.managerid));
var associates = empList.Where(e => e.managerid != null && managers.Any(m => m.employeeid == e.managerid));
PrintList(associates, "Associates");
PrintList(managers, "managers");
PrintList(heads, "heads");
Console.ReadKey();
}
private static void PrintList(IEnumerable<Employee> list, string name)
{
System.Console.WriteLine(name);
foreach (var item in list)
{
System.Console.WriteLine(item);
}
}
}
public class Employee
{
public Employee(int empid, string fname, int? mid = null)
{
employeeid = empid;
firstname = fname;
lastname = fname;
emailid = "[email protected]";
managerid = mid;
createdOn = DateTime.Now;
}
public int employeeid { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
public string emailid { get; set; }
public int? managerid { get; set; }
public DateTime createdOn { get; set; }
public static IEnumerable<Employee> GetTestData()
{
return new List<Employee>
{
new Employee(1, "Emp-1-A", 3),
new Employee(2, "Emp-2-A", 3),
new Employee(3, "Emp-3-M", 5),
new Employee(4, "Emp-4-M", 5),
new Employee(5, "Emp-5-H", null),
new Employee(6, "Emp-6-A", 8),
new Employee(7, "Emp-7-A", 8),
new Employee(8, "Emp-8-M", 10),
new Employee(9, "Emp-9-M", 10),
new Employee(10, "Emp-10-H", null),
new Employee(11, "Emp-11-A", 4),
new Employee(12, "Emp-12-A", 4),
new Employee(13, "Emp-13-A", 9),
new Employee(14, "Emp-14-A", 9),
};
}
public override string ToString()
{
return $"Id: {employeeid}, Name: {firstname}, ManagerId: {managerid}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment