How can I optimise a foreach calling an API? The code calls an API and returns the first string reponse I have the following code that makes a call to an external API, processes the response and returns a string. The problem is it is taking a very long time to process. I can't do anything to the API, but I was just wondering if there is a better way of doing the rest of the code.
foreach(var item in products)
{
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink);
}

And the GetSiteLink method in a different class.
public async Task&lt;string&gt; GetSiteLink(int itemId, string baseLink)
{
    var encodedUrl = HttpUtility.UrlEncode(baseLink);
    var response = await _client.GetAsync($&quot;apilink/{itemId}/?ulp={encodedUrl}&quot;);
    if (response.IsSuccessStatusCode)
    {
        var responseContent = await response.Content.ReadAsStringAsync();
        var parsedResponse = JsonConvert.DeserializeObject&lt;string[]&gt;(responseContent);
        return HttpUtility.UrlDecode(parsedResponse[0]);
    }
    return &quot;&quot;;
}
one way of solving this would be using Task.WhenAll the idea is to add all tasks into a list of tasks then we call Task.WhenAll and await the final results.
Here is an example of it :
private async Task&lt;ProductItem&gt; SetSiteLink(ProductItem item)
{   
    item.site = await _testRepo.GetSiteLink(item.Id, item.baseLink); 
    
    return Task.FromResult(item);  
}

then call it like this :
var tasks = new List&lt;Task&lt;ProductItem&gt;&gt;();

foreach (var item in products)
{
    tasks.Add(SetSiteLink(item));
}

var results = await Task.WhenAll(tasks);