简体   繁体   English

当两个列表的类型不同时,如何将每个循环的嵌套转换为Linq

[英]How to convert a nested for each loop into Linq when the two lists are of different types

I want to convert a nested foreach loop in C# to Linq. 我想将C#中的嵌套foreach循环转换为Linq。 I know how to do it if the two lists are of same type. 如果两个列表的类型相同,我知道该怎么做。 But in my case, they are of different type, except that they both have two common properties, DocumentId and IsValid. 但就我而言,它们具有不同的类型,除了它们都有两个公共属性,DocumentId和IsValid。 I have to loop through the outer list and the inner list and whenever the DocumentId of both are the same, then assign the IsValid value from the outer loop object to the inner loop object. 我必须遍历外部列表和内部列表,并且只要两者的DocumentId都相同,然后将IsValid值从外部循环对象分配给内部循环对象。 I have the following foreach loop is working fine. 我有以下foreach循环工作正常。

foreach (var docs in outerDocuments)
{
     foreach (var presentedDocuments in innerdocuments)
     {
           if (docs.DocumentId.Equals(presentedDocuments.DocumentId))
           {
                 presentedDocuments.IsValid = docs.IsValid;
           }
     }
}

I need to convert it to Linq. 我需要将其转换为Linq。 Usually ReSharper does a good job of refactoring such code. 通常,ReSharper会很好地重构此类代码。 But in this case it converted only the nested foreach to Linq, and even then it threw a warning , "Access to foreach variable in closure". 但是在这种情况下,它仅将嵌套的foreach转换为Linq,甚至发出警告:“访问闭包中的foreach变量”。

Thanks 谢谢

You can try using Enumerable.Join : 您可以尝试使用Enumerable.Join

foreach (var item in outerDocuments.Join(innerdocuments,
                                         outer => outer.DocumentId,
                                         inner => inner.DocumentId,
                                         (outer, inner) => new { OuterDoc = outer, InnerDoc = inner }))
{
    item.InnerDoc.IsValid = item.OuterDoc.IsValid;
}

Try this: 尝试这个:

foreach (var presentedDocuments in innerdocuments)
{
    var doc = outerDocuments.FirstOrDefault(a => a.DocumentId.Equals(presentedDocuments.DocumentId));
    if (doc != null)
    {
        presentedDocuments.IsValid = doc.IsValid;
    }
}

You can use .Join() extension method and do it in one line like this: 您可以使用.Join()扩展方法,并像这样在一行中完成此操作:

outerDocuments.Join(innerDocuments, o => o.DocumentId, i => i.DocumentId, (o, i) =>  i.IsValid = o.IsValid).ToList();

As noted by @sstan .ToList() call is required to force enumeration. 正如@sstan所指出的那样,需要调用.ToList()来强制枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM