2017-09-22 116 views
-2

我有兩組數據:trainedOfficersofficersToTrain。這些數據集共用一個ClubId。我試圖確保trainedOfficers不會出現在officersToTrain中,所以我想執行正確的外連接。綜觀這一形象:如何使用linq執行右連接外連接

enter image description here

  • A = trainedOfficers
  • B = officersToTrain

我曾嘗試做下面的查詢,但它產生任何結果。

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

這沒有測試,但我認爲它應該工作。你不止一次地使用過軍官。

編輯: 不知道爲什麼你會需要兩個表。你可以在軍官表中標記'IsTrained'。然後爲了顯示誰是訓練vs不是,你可以關閉那個場。

+0

完全同意最後一段。這是一個糟糕的設計。 –