I have a question about good practice with async-await in foreach loop.
My method looks like this
public async Task<List<Category>> GetCategoriesAsync(string partOfName, CancellationToken ct = default(CancellationToken)) { string lowerCasePartOfName = partOfName.ToLower(); var categories = await _context.ECATEGORIES .Where(a => a.NAME.ToLower().Contains(lowerCasePartOfName)) .ProjectTo<Category>() .ToListAsync(ct); //version1 #Beginning var i = 0; foreach (var parentId in categories) { var categoryParent = await _context.ECATEGORIES .Where(a => a.ID == parentId.ParentId) .Select(s => s.NAME) .FirstOrDefaultAsync(ct); categories[i].CategoryParent = categoryParent; i++; } //version1 #End //version2 #Beginning categories.ForEach(async x => x.CategoryParent = await _context.ECATEGORIES .Where(a => a.ID == x.ParentId) .Select(s => s.NAME).FirstOrDefaultAsync(ct)); //version2 #End return categories; } Version1 and version2 gives same result but I would like to ask which is better practice for async tasks or maybe none of them.
Thanks in advance.