Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion between IEnumerable to IList (Dapper return result)

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?

like image 987
Maxim Zhukov Avatar asked Feb 08 '14 13:02

Maxim Zhukov


2 Answers

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();
}
like image 75
Marc Gravell Avatar answered Nov 04 '22 20:11

Marc Gravell


Just call .ToList() on it?

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

like image 29
David Avatar answered Nov 04 '22 19:11

David