如何在LINQ中使用Join重写两个表的SQL Union?

MaY*_*YaN 5 c# linq

我有 3 个课程,如下所示:

public class A
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string Age {get; set;}
    public bool IsEmployed {get; set;}
    public int RoleId {get; set;}
}

public class B
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string Age {get; set;}
    public int RoleId {get; set;}
}

public class Roles
{
    public int Id {get; set;}
    public string RoleName {get; set;}
    ...
}
Run Code Online (Sandbox Code Playgroud)

假设这些类在 DBMS 上有自己的表。

我目前有一个 SQL 查询,我想用 LINQ 重写它(尽可能优雅)

SELECT A.Name, A.Age, Roles.RoleName, A.IsEmployed 
FROM A 
JOIN Roles ON A.RoleId = Roles.Id
WHERE Roles.RoleName = 'ADMIN'

UNION

SELECT B.Name, B.Age, Roles.RoleName, '-' as IsEmployed 
FROM B 
JOIN Roles ON B.RoleId = Roles.Id
WHERE Roles.RoleName = 'ADMIN'
Run Code Online (Sandbox Code Playgroud)

目前我已经设法将其重写为:

var filteredClassA = from c in allClassAs
    join role in allRoles on role.Id equals c.RoleId
    where role.RoleName == "ADMIN"
    SELECT new {c.Name, c.Age, role.RoleName, c.IsEmployed};

var filteredClassB = from c in allClassBs
    join role in allRoles on role.Id equals c.RoleId
    where role.RoleName == "ADMIN"
    SELECT new {c.Name, c.Age, role.RoleName, IsEmployed = "-"};
Run Code Online (Sandbox Code Playgroud)

然后我可以将结果合并或合并到一个变量中,如下所示:

var result = filteredClassA.Union(filteredClassB);
Run Code Online (Sandbox Code Playgroud)

我不喜欢这个解决方案,有没有更好的方法可以在单个 LINQ 查询中完成上述所有操作?

提前致谢。

小智 5

另一种选择,仅在一个查询中:

var result = allClassAs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, c.IsEmployed})
                        .Where(r => r.RoleName == "ADMIN")
                        .Union(allClassBs.Join(allRoles, c => c.Id, role => role.Id, (c, role) => new {c.Name, c.Age, role.RoleName, IsEmployed = "-"})
                        .Where(r => r.RoleName == "ADMIN"));
Run Code Online (Sandbox Code Playgroud)