user16695025
user16695025

Reputation:

foreach in foreach list c#

The GalleryDetail.Id is 148 when it enters the first foreach loop, and the GalleryDetail.Id is 148 when it enters the second foreach loop. But it does not enter the first foreach loop again. It continues from the second. How do I get it to re-enter the first loop here?

NOTE: I do not have direct access from the GalleryDetail.Id request.

var detailList = await _repo.GalleryDetail.GetAllAsync();

foreach (var item in mapped.GalleryDetails)
{
    foreach (var item2 in detailList)
    {
        if (item.Id != item2.Id)
        {
            var mapped3 = _mapper.Map<GalleryDetails>(item2);
            await _repo.GalleryDetail.DeleteAsync(mapped3);
        }
    }
}

Upvotes: 1

Views: 1064

Answers (1)

Viettel Solutions
Viettel Solutions

Reputation: 1479

It's not necessary to use 2 loop here, you can use LinQ instead. And you should not leave async Delete inside foreach loop, because it will connect to you database mutiple time. Example:

var detailList = await _repo.GalleryDetail.GetAllAsync();
//Map the whole list
var detailListMapped = _mapper.Map<List<GalleryDetails>>(detailList);
//Use LinQ to find database items not in request
var deletedList = detailListMapped.Where(x => !mapped.GalleryDetails.Any(y => y.Id == x.Id)).ToList();
//Entity Framework have RemoveRange function, you should use it here
await _repo.GalleryDetail.RemoveRangeAsync(deletedList );

Upvotes: 5

Related Questions