简体   繁体   English

IEnumerable到IList之间的转换(Dapper返回结果)

[英]Conversion between IEnumerable to IList (Dapper return result)

There is signature of UserManager method (ASP .NET Identity Core default implementation): UserManager方法的签名(ASP .NET Identity Core默认实现):

public Task<IList<string>> GetRolesAsync(User user) {
    const string query = @"
                select r.[Name]
                  from [UserRoles] ur
             left join [Roles] r on r.RoleId = ur.RoleId
                 where ur.UserId = @userId;
    ";

    return Task.Factory.StartNew(() => {
        using (SqlConnection connection = new SqlConnection(_connectionString))
            return connection.Query<string>(query, new { userId = user.UserId });
    });
}

But unfortunately Dapper.Query<T> returns IEnumerable<T> . 但不幸的是, Dapper.Query<T>返回IEnumerable<T>

Is it possible to return IList<T> or i have to make conversion myself? 是否可以返回IList<T>或者我必须自己进行转换?

Dapper only guarantees to hand you an IEnumerable<T> . Dapper只保证向您提供IEnumerable<T> So you should only assume that. 所以你应该只假设这一点。 In particular, it already has different scenarios where it can give you either a populated list, or a deferred iterator. 特别是,它已经拥有了不同的场景中它可以给你无论是填充的列表, 延期迭代器。

The simplest approach is to just call .ToList() . 最简单的方法是调用.ToList() If you are intent on avoiding an alloc, then maybe do a speculative test: 如果您打算避免使用alloc,那么可以进行推测测试:

static IList<T> SpeculativeToList<T>(this IEnumerable<T> source)
{
    return source as IList<T> ?? source.ToList();
}

Just call .ToList() on it? 只需调用.ToList()就可以了吗?

return connection.Query<string>(query, new { userId = user.UserId }).ToList();

This would enumerate the IEnumerable<T> and create an in-memory copy of all elements found as a List<T> . 这将枚举IEnumerable<T>并创建作为List<T>找到的所有元素的内存中副本。

尝试使用显式强制转换

return (IList<string>)connection.Query<string>(query, new { userId = user.UserId });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM