Conversion between IEnumerable to IList (Dapper return result)

.net asp.net-mvc c# dapper

Question

There is signature of UserManager method (ASP .NET Identity Core default implementation):

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>.

Is it possible to return IList<T> or i have to make conversion myself?

Accepted Answer

Try to use an explicit cast

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

Expert Answer

Dapper only guarantees to hand you an 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(). If you are intent on avoiding an alloc, then maybe do a speculative test:

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


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why