如何使用linq执行正确的连接外连接

时间:2017-09-22 17:58:03

标签: c# linq outer-join right-join

我有两组数据:trainedOfficersofficersToTrain。这些数据集共享ClubId。我正在尝试确保trainedOfficers中没有出现officersToTrain,因此我想执行正确的外连接。看这张图片:

enter image description here

  • A =训练有关的办公室
  • B = officerToTrain

我尝试过以下查询,但没有结果。

public void SetTrainedClubOfficers(ILookup<ClubID, ClubOfficerAuthority> clubsAuthorityLookup)
{
    var clubIds = clubsAuthorityLookup.Select(x => x.Key);
    var trainedOfficers = GetTrainedClubOfficers(clubIds.ToArray());
    var clubsToTrain = from trainedOfficer in trainedOfficers
                       join officer in clubsAuthorityLookup
                       on trainedOfficer.Key equals officer.Key into joined
                       from officer in joined.DefaultIfEmpty()
                       select new
                       {
                           ClubId = officer.Key,
                           Officers = officer.Select(club => club)
                       };
}

如何获得正确的外部联接?

1 个答案:

答案 0 :(得分:1)

    public void SetTrainedClubOfficers(ILookup<ClubID, ClubOfficerAuthority> clubsAuthorityLookup)
        {
            var clubIds = clubsAuthorityLookup.Select(x => x.Key);
            var trainedOfficers = GetTrainedClubOfficers(clubIds.ToArray());
            var clubsToTrain = from trainedOfficer in trainedOfficers
                               join officer in clubsAuthorityLookup
                               on trainedOfficer.Key equals officer.Key into joined
                               from j in joined.DefaultIfEmpty()
                               select new
                               {
                                   ClubId = j.Key,
                                   Officers = officer.Select(club => club)
                               };
}

这未经过测试,但我认为应该可行。你不止一次使用军官。

编辑: 不知道为什么你需要两张桌子呢。你可以在Officers表中只有一个标记'IsTrained'的字段。然后,为了显示被训练的人与否,你可以关闭那个领域。