这里有一个简单的例子。
模型:
class Employee
{
public string Name { get; set; }
public int ID { get; set; }
public int ProjectID { get; set; }
}
class Project
{
public int ProjectID { get; set; }
public string ProjectName { get; set; }
}
方法:
public void LeftRightJoin()
{
List<Project> ListOfProjects = new()
{
new(){ ProjectID = 1, ProjectName = "UID" },
new(){ ProjectID = 2, ProjectName = "RBS" },
new(){ ProjectID = 3, ProjectName = "XYZ" },
};
List<Employee> ListOfEmployees = new(){
new(){ ID = 1, Name = "Sunil", ProjectID = 1 },
new(){ ID = 1, Name = "Anil", ProjectID = 1 },
new(){ ID = 1, Name = "Suman", ProjectID = 2 },
new(){ ID = 1, Name = "Ajay", ProjectID = 3 },
new(){ ID = 1, Name = "Jimmy", ProjectID = 4 }
};
var Ljoin = from emp in ListOfEmployees
join proj in ListOfProjects
on emp.ProjectID equals proj.ProjectID into JoinedEmpDept
from proj in JoinedEmpDept.DefaultIfEmpty()
select new
{
EmployeeName = emp.Name,
ProjectName = proj?.ProjectName
};
var RJoin = from proj in ListOfProjects
join employee in ListOfEmployees
on proj.ProjectID equals employee.ProjectID into joinDeptEmp
from employee in joinDeptEmp.DefaultIfEmpty()
select new
{
EmployeeName = employee?.Name,
ProjectName = proj.ProjectName
};
Console.WriteLine(string.Join("\n", Ljoin.Select(emp => $" Employee Name = {emp.EmployeeName}, Project Name = {emp.ProjectName}")));
Console.WriteLine(string.Join("\n", RJoin.Select(emp => $" Employee Name = {emp.EmployeeName}, Project Name = {emp.ProjectName}")));
}