Home > OS >  c# Linq expression to replace foreach with multiple awaits
c# Linq expression to replace foreach with multiple awaits

Time:02-03

I am trying to determine if there is a linq expression equivalent of the following foreach statement below?

Two of the several solutions I've tried are commented with their results below the loop. I thought the first example or a variation would work but the type is always IEnumerable<Task> unless I call it synchronously which just feels apprehensive.

public async Task<IEnumerable<CompanySettings>> GetClientSettingsAsync()
{
    foreach(var company in await GetParticipatingCompaniesAsync())
    {
        settings.Add(new CompanySettings(company, await GetSyncDataAsync(company)));
    }

    // a's Type is IEnumerable<Task<CompanySetting>> and not IEnumerable<CompanySetting>
    // var a = (await GetParticipatingCompaniesAsync()).Select(async x => new CompanySettings(x, await GetSyncDataAsync(x)));
    // return a;


    // b's Type is correct it's also synchronous.  Does that matter?
    // var b = (GetParticipatingCompaniesAsync()).Result.Select(x => new CompanySettings(x, GetSyncDataAsync(x).Result));
    //return b;

    return settings;
}

CodePudding user response:

You are close with your first attempt, you just need to await the tasks that are returned

async Task<IEnumerable<CompanySettings>> GetClientSettingsAsync() {

    var companies = await GetParticipatingCompaniesAsync();
    var companySettings = companies.Select(async company =>
        new CompanySettings(company, await GetSyncDataAsync(company))
    );

    return await Task.WhenAll(companySettings);
}

CodePudding user response:

Yes, you can use Select to achieve the same result

Here is one way to do it:

public async Task<IEnumerable<CompanySettings>> GetClientSettingsAsync()
{
    var companies = await GetParticipatingCompaniesAsync();
    var companySettingsTasks = companies.Select(async company => 
        new CompanySettings(company, await GetSyncDataAsync(company)));
    var settings = await Task.WhenAll(companySettingsTasks);
    return settings;
}
  • Related