加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

迭代任务列表C#

发布时间:2020-12-16 01:28:27 所属栏目:百科 来源:网络整理
导读:我有这样的代码 public async TaskListUser GetUsersByField(string fieldName,string fieldValue) { var filter = BuildersUser.Filter.Eq(fieldName,fieldValue); var result = await _usersCollection.Find(filter).ToListAsync(); return result.ToList(
我有这样的代码

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读