【问题标题】:How Do I Return IList<T> From ICollection<T>如何从 ICollection<T> 返回 IList<T>
【发布时间】:2015-10-24 22:22:44
【问题描述】:

我有以下方法:

    public Task<IList<string>> GetRolesAsync(AppUser user)
    {
        if(user.Roles == null)
        {
            // TODO: Load roles
        }

            //Not sure return syntax to return user.Roles as IList<string>
            return Task.FromResult<List<string>>(???);
    }

其中user.Roles 的类型为ICollection&lt;IAppRole&gt;,上面的方法返回IList&lt;string&gt; 的类型。我无法进行转换,然后找到正确的语法来进行返回。

【问题讨论】:

  • 您如何期望IAppUser 变成string
  • 这是我的问题中的一个错误,我刚刚更正了,IAppUser 应该是 IAppRole,该方法将获取角色集合并将它们作为字符串值列表(只是名称)返回这是Identity 2 UserStore 自定义存储实现。
  • 那么为什么不返回List&lt;IAppRole&gt;呢?
  • 返回必须是IList&lt;string&gt;,因为这是身份2 UserStore 中使用的接口IUserRoleStore&lt;AppUser, int&gt; 的实现。
  • 希望对为什么投反对票发表评论?从我目前的声誉可以看出,我不经常参与,但是,我想开始并且当然提供有意义的问题和答案。谢谢!

标签: c# generics collections task-parallel-library


【解决方案1】:

这会将角色列表转换为字符串列表:

user.Roles.Select(r => r.Name).ToList();

返回任务:

return Task.FromResult(user.Roles.Select(r => r.Name).ToList());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多