0

In method GeExistingDbList(), what's an easy way to convert from Task<list<object>> to just list<differentobject>. I'm getting error:

"foreach statement cannot operate on variables of type Task<list<Connection>>. does not contain a public instance or extension definition for GetEnumerator".

Do I have to declare a numerator object: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs1579?f1url=%3FappId%3Droslyn%26k%3Dk(CS1579)

    public class ExistingDb
    {
        public string DBName { get; set; }
        public Guid Id { get; set; }
    }

    public List<ExistingDb> GeExistingDbList()
    {
        List<ExistingDb> existingDbList = new List<ExistingDb>();
        Task<List<Connection>> connectionsList = GetConnections(ADMIN_TOKEN);

        foreach (var conn in connectionsList)
        {
            existingDbList.Add(new ExistingDb() { 
                    DBName = conn.DatabaseName, Id = conn.Id });
        }

        return existingDbList;
    }

   private async Task<List<Connection>> GetConnections(string authToken)
    {
        string action = $"connection";
        try
        {
           var result = await GetAsync<List<Connection>>(action, authToken);
            return result;
        }
        catch
        {
            return null;
        }
    }
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • `Task<>` needs to be `await`ed. Really, once you start using await/async, you should do it throughout your code. Rule of thumb, if a function is `async`, it should have a name suffix of Async, to remind you to `await` it. – Neil Mar 21 '22 at 22:40
  • If I make everything Task<> & await, how do I resolve the lack of iterator in the foreach loop? –  Mar 21 '22 at 22:48
  • The only reason you can't `foreach` it is because you didn't await it, so its type is a `Task` instead of your list. Just await it and it'll just work. – Kirk Woll Mar 21 '22 at 22:54
  • Side note: text/title of the question does not match the code - there types look the same in the code while title asks for conversion from `List` too (use https://stackoverflow.com/questions/8933434/how-to-cast-listobject-to-listsomethingelse if you actually need that) – Alexei Levenkov Mar 21 '22 at 22:58

0 Answers0