string? contract = null;var contractsPrio1 = await GetContractsPrio1(client);contract = contractsPrio1.FirstOrDefault();if (contract is null){ var contractsPrio2 = await GetContractsPrio2(client); contract = contractsPrio2.FirstOrDefault();}if (contract is null){ var contractsPrio3 = await GetContractsPrio3(client); contract = contractsPrio3.FirstOrDefault();}
string? contract = null;var contractsPrio1 = await GetContractsPrio1(client);contract = contractsPrio1.FirstOrDefault();if (contract is null){ var contractsPrio2 = await GetContractsPrio2(client); contract = contractsPrio2.FirstOrDefault();}if (contract is null){ var contractsPrio3 = await GetContractsPrio3(client); contract = contractsPrio3.FirstOrDefault();}
I think my intention is clear, I have several ways to query contracts that are prioritized a certain way. If i dont find anything in the first priority list, check the 2nd, if i dont find anything, check the 3rd and so on.
I got this so far
async Task<T?> SetToFirstElement<T>(List<Func<Task<List<T>>>> getElementsFunctions) where T : class{ foreach (var getElementsFunction in getElementsFunctions) { var elements = await getElementsFunction.Invoke(); if (elements.Any()) return elements.First(); } return null;}
async Task<T?> SetToFirstElement<T>(List<Func<Task<List<T>>>> getElementsFunctions) where T : class{ foreach (var getElementsFunction in getElementsFunctions) { var elements = await getElementsFunction.Invoke(); if (elements.Any()) return elements.First(); } return null;}
Are there any issues with this? Does this work simpler? Working with tasks and lists of tasks and async await is always kinda dangerous. But it seems to work. The
GetContractsPrioX
GetContractsPrioX
methods fire only if needed. If I have an exception in one of them, everything seems to behave normally, nothing gets swallowed.
I would like to remove the () => part, but I dont think its possible. If I remove it and just work with the
GetContractsPrioX
GetContractsPrioX
methods directly, the tasks naturally start executing instantly.