Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Task List C#

I have code like this

public async Task<List<User>> GetUsersByField(string fieldName, string fieldValue)
    {
        var filter = Builders<User>.Filter.Eq(fieldName, fieldValue);
        var result = await _usersCollection.Find(filter).ToListAsync();

        return result.ToList();
    }

When I trying to iterate it using

foreach(var w in GetUsersByField("Name", John"))

it shows error that

"does not contain a public definition for 'GetEnumerator'"

I have tried using

public async IEnumerable<Task<List<User>>> GetUsersByField(string fieldName, string fieldValue)

but still shows error. Any suggestions?

like image 805
Skipm3 Avatar asked Jan 26 '23 20:01

Skipm3


1 Answers

With an async method like this:

public async Task<List<User>> GetUsersByField(string fieldName, string fieldValue

It's advisable to await it:

public async Task MyCallingMethod()
{
    var users = await GetUsersByField(...);

    foreach(var w in users ) 
    {
       ...
    }
}

or:

public async Task MyCallingMethod()
{
    foreach(var user in await GetUsersByField(...)) 
    { 
       ... 
    }
}

There are other ways by calling Result, though let's not go down that rabbit hole.

In short, let your Async Await Pattern propagate like a virus through your code.


Additional reading

Stephen Cleary : Async and Await

like image 104
TheGeneral Avatar answered Feb 02 '23 00:02

TheGeneral