Home > OS >  Update foreach in foreach c#
Update foreach in foreach c#

Time:01-15

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. 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);
            }
        });

enter image description here enter image description here enter image description here

CodePudding user response:

This overwrites a.Image for every item in listDetail, therefore you get the last Image:

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

As you have an Id property, I suggest using it for synchronization:

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

I added a break; so you break out of the loop as soon as you found a match.

  •  Tags:  
  • Related