简体   繁体   English

在 foreach c# 中更新 foreach

[英]Update foreach in foreach c#

The code snippet shown will compare each element in the first list with one element in the second one.显示的代码片段会将第一个列表中的每个元素与第二个列表中的一个元素进行比较。 But when the inner foreach finishes, the upper foreach re-enters and the image throws the same guid in both lists.但是当内部 foreach 完成时,上部 foreach 重新进入并且图像在两个列表中抛出相同的 guid。 How can I get it to not do this?我怎样才能让它不这样做?

   var listDetail = await _repo.GalleryDetail.GetAllAsync(a => a.GalleryId == request.Id);

        request.GalleryDetails.ToList().ForEach(a =>
        {
            if (a.File == null) 
            {
                foreach (var item in listDetail)
                {
                    a.Image = item.Image;
                }
            }
            else
            {
                foreach (var item in listDetail)
                {
                    if (item.Image != null && item.Image != "True")
                        item.Image = a.File.DeleteFtp(url: item.Image.Substring(7), 
          cdn).ToString();
                }

                a.Image = a.File.UploadFtp("GalleryDetail", cdn);
            }
        });

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

This overwrites a.Image for every item in listDetail , therefore you get the last Image :a.Image listDetail因此您将获得最后一个Image

foreach (var item in listDetail)
{
    a.Image = item.Image;
}

As you have an Id property, I suggest using it for synchronization:由于您有一个Id属性,我建议使用它进行同步:

foreach (var item in listDetail)
{
    if (item.Id == a.Id)
    {
        a.Image = item.Image;
        break;
    }
}

I added a break;我加了一个break; so you break out of the loop as soon as you found a match.因此,一旦找到匹配项,您就会跳出循环。

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

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