首页 > 解决方案 > 如何使用 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

标签: c#linq

解决方案


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

无需使用ToListonresult1result2。通过这样做,联合可以在持久层中解析(如果这是 EF)。


推荐阅读