c# - 如何使用 Union 组合两个 linq 查询
问题描述
我有两个Merge
我想使用的 Linq 查询,Union
我该怎么做
查询 1
var result = (from pni in _entities.PushNotificationInfoes
join ssg in _entities.StudentStaffGuardians on pni.UniqueID equals ssg.StaffId
join st in _entities.Students on ssg.StudentId.GetValueOrDefault() equals st.StudentID
where st.OrganizationID == orgId
select new
{
pni.UserID,
pni.PNToken,
pni.OSType,
}).ToList()
查询 2
var result = (from pni in _entities.PushNotificationInfoes
join ssg in _entities.StudentGuardians on pni.UniqueID equals ssg.StaffId
join st in _entities.Students on ssg.StudentId.GetValueOrDefault() equals st.StudentID
where st.OrganizationID == orgId
select new
{
pni.UserID,
pni.PNToken,
pni.OSType,
}).ToList()
直接怎么办,从查询一个就好了}).ToList().Union
?
解决方案
var result1 = (from pni in _entities.PushNotificationInfoes
join ssg in _entities.StudentStaffGuardians on pni.UniqueID equals ssg.StaffId
join st in _entities.Students on ssg.StudentId.GetValueOrDefault() equals st.StudentID
where st.OrganizationID == orgId
select new
{
pni.UserID,
pni.PNToken,
pni.OSType,
});
var result2 = (from pni in _entities.PushNotificationInfoes
join ssg in _entities.StudentGuardians on pni.UniqueID equals ssg.StaffId
join st in _entities.Students on ssg.StudentId.GetValueOrDefault() equals st.StudentID
where st.OrganizationID == orgId
select new
{
pni.UserID,
pni.PNToken,
pni.OSType,
});
var result = result1.Union(result2).ToList();
无需使用ToList
onresult1
和result2
。通过这样做,联合可以在持久层中解析(如果这是 EF)。