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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With