我有这样的代码 public async TaskListUser GetUsersByField(string fieldName, string fieldValue) { var filter = BuildersUser.Filter.Eq(fieldName, fieldValue); var result = await _usersCollection.Find(filter).ToListAsync(); return result
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(); }
当我尝试使用迭代它时
foreach(var w in GetUsersByField("Name", John"))
它显示错误
“does not contain a public definition for ‘GetEnumerator'”
我试过用
public async IEnumerable<Task<List<User>>> GetUsersByField(string fieldName, string fieldValue)
但仍显示错误.有什么建议?
使用这样的异步方法public async Task<List<User>> GetUsersByField(string fieldName, string fieldValue
建议等待它
public async Task MyCallingMethod() { var users = await GetUsersByField(...); foreach(var w in users ) { ... } }
要么
public async Task MyCallingMethod() { foreach(var user in await GetUsersByField(...)) { ... } }
通过调用Result还有其他方法,但不要让那个兔子洞掉下来
简而言之,让Async Await Pattern通过代码像病毒一样传播
补充阅读
Stephen Cleary:Async and Await