You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C# LINQ实现IN条件查询?解决IQueryable转List报错

问题解决方法

你的代码报错核心原因是:LINQ查询返回的是IQueryable<string>类型,而你试图直接赋值给List<string>类型的变量,两者无法隐式转换。

修正代码有两种常用方式:

同步查询(适用于同步场景)

在查询末尾调用ToList()方法,将IQueryable<string>转换为List<string>:

List<string> roleNameList = _dbContext
    .Roles
    .Where(r => idRoles.Contains(r.RoleId))
    .Select(r => r.RoleName)
    .ToList();

异步查询(推荐在EF Core中使用,避免阻塞线程)

如果是异步上下文,调用ToListAsync()方法(需要引用Microsoft.EntityFrameworkCore命名空间):

List<string> roleNameList = await _dbContext
    .Roles
    .Where(r => idRoles.Contains(r.RoleId))
    .Select(r => r.RoleName)
    .ToListAsync();

另外需要确认:你的idRoles确实是List<short>或者IEnumerable<short>类型,和数据库中RoleId的short类型匹配,这部分你的写法是正确的,不需要调整。

内容的提问来源于stack exchange,提问作者user18363545

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:52:01