优雅的lambda LINQ

时间:2016-07-19 13:30:35

标签: c#

问候我遇到了一个小问题,我在这里遇到了一个非常讨厌的三重奏:

List<Attachment> docAttachments = new List<Attachment>();
foreach (DocumentAttachment document in attachmentToAddTestRun)
{
    foreach (Attachment attachment in document.Attachments)
    {
        foreach (DocumentAttachment tDocument in TargetDocumentAttachmentMeta)
        {
            if (tDocument.Attachments.Contains(attachment) && docAttachments.Contains(attachment)) continue;
            docAttachments.Add(attachment);
        }
    }
}

现在有一种方法可以将它转换为优雅的Lamba表达式到目前为止我已经进行了简单的查询尝试但是它比foreach更难以读取:

List<Attachment> docAttachments = new List<Attachment>();
foreach (Attachment attachment in from document 
in attachmentToAddTestRun from attachment 
in document.Attachments from tDocument 
in TargetDocumentAttachmentMeta 
where !tDocument.Attachments.Any(tDoc => !CompareTuple(tDoc, attachment)) 
|| !docAttachments.Any(doc => !CompareTuple(doc, attachment)) select attachment)
            {
                docAttachments.Add(attachment);
            }

1 个答案:

答案 0 :(得分:2)

首先获取所有附件的列表:

var allAttachments = attachmentToAddTestRun.SelectMany(x => x.Attachments);

现在,您可以与TargetDocumentAttachmentMeta的附件相交:

var allAttachmentsFromMeta = TargetDocumentAttachmentMeta.SelectMany(x => x.Attachments);
var docAttachments = allAttachments.Except(allAttachmentsFromMeta);

如果您更喜欢 compact 版本:

var docAttachments = attachmentToAddTestRun.SelectMany(x => x.Attachments)
    .Except(TargetDocumentAttachmentMeta.SelectMany(x => x.Attachments))
    .ToList();