2016-07-27 88 views
2

問候我有一個邏輯問題,我有2個程序結合2個LINQ操作

首先是LINQ,看起來像:

_sharedDocumentsAttachments = SourceDocumentAttachmentMeta 
.Where(sDoc => TargetDocumentAttachmentMeta.Any(tDoc => tDoc.DocumentBridgeId == sDoc.DocumentId)).ToList(); 

List<DocumentAttachment> _sharedDocumentsAttachments; 

而且

SharedDocumnentAttachmentConnector = new Dictionary<int, int>(); 
foreach (DocumentAttachment document in _sharedDocumentsAttachments) 
{ 
    foreach (DocumentAttachment tDoc in TargetDocumentAttachmentMeta.Where(tDoc => document.DocumentId == tDoc.DocumentBridgeId)) 
    { 
     SharedDocumnentAttachmentConnector.Add(document.DocumentId, tDoc.DocumentId); 
    } 
} 

而我很好奇g如果我可以以某種方式將第二個過程附加到第一個過程,因爲基本上它們正在做相同的比較,但將值添加到2個不同的集合中?

我正在試驗每個,但它不會正常工作。

回答

2

你可以這樣做:加入兩個集合,然後指定轉換如何字典

_sharedDocumentsAttachments.Join(TargetDocumentAttachmentMeta, 
           document => document.DocumentId, 
           tDoc => tDoc.targetDocument, 
           (document, tDoc) => new 
           { 
            Key = document.DocumentId, 
            Value = tDoc.DocumentId 
           }) 
          .ToDictionary(item => item.Key, 
              item => item.Value); 

注意到,如果加入將導致2「記載」爲同一document.DocumentId將拋一個ArgumentException: An item with the same key has already been added

如果可能發生的事情,然後想:

  1. 將其保存爲LookUp
  2. 將其保存爲Dictionary<int,IEnumerable<int>>

對於兩個check this

之間的差異