返回方法调用之前更新本地 iqueryable 列表

Dys*_*Guy 2 c# linq collections foreach

在我原来的帖子《Using Foreach on iQueryable List find value if in 2nd List》的后续问题中,我无法找到解决方案,当我使用 foreach 循环进行更改时,它会更新本地列表。浏览我的 Visual Studio 调试器,如果在 LookForMe 列表中找到当前项目,它会更新 item.LinkURL 值。但是,当将 Results.ToList() 返回到我的调用方法时,此更新不在返回的集合中。在返回之前如何将它们保存到结果列表中?没有看到任何智能感知,比如 Results.Update() 或 Results.Save() 可以工作。

  foreach (var item in Results)
        {
            if (LookForME.Any(fs => item.LinkUrl.Contains(fs)))
            {
                item.LinkUrl = ServerPath + "/" + item.LinkUrl;   
                // works great until its time to return the updated Results list                 
            }
               // something here to update results with new value?
        }

        return Results.ToList();
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 5

您需要首先使用迭代ToList并修改内存列表并返回该列表。

目前您的ResultIQueryable 更像是一个查询)尚未执行。

你可以这样做:

var newList = Result.ToList(); //get a in-memory list
foreach (var item in newList) //modify in-memory list
{
        if (LookForME.Any(fs => item.LinkUrl.Contains(fs)))
        {
            item.LinkUrl = ServerPath + "/" + item.LinkUrl;   
            // works great until its time to return the updated Results list                 
        }
           // something here to update results with new value?
}

return newList;  
Run Code Online (Sandbox Code Playgroud)

  • 很有道理。延迟执行又让我了?> :-) 非常感谢。 (2认同)