如何使用Union合并两个linq查询

时间:2018-11-13 12:00:11

标签: c# 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的查询中进行操作?

2 个答案:

答案 0 :(得分:3)

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();

无需在ToListresult1上使用result2。通过这种方式,联合可以在持久层(如果是EF)中进行解析。

答案 1 :(得分: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,

  })
  .Union(
    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()之前的所有查询文本仅是查询组成。当您认为查询已完成并准备执行时,应调用.ToList()