2016-07-27 60 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

之间的差异