【问题标题】:Cannot convert lambda expression to intended delegate type (list of ints contains int)无法将 lambda 表达式转换为预期的委托类型(int 列表包含 int)
【发布时间】:2018-08-30 22:00:11
【问题描述】:

我有一个接收字符串数组的方法。然后我把它变成一个整数列表。最后,我创建了一个 IQueryable,我想在其中返回与关联表中的 ID 匹配的结果。

public myMethod(string[] locationRoleids){
IQueryable<equipment> result = DbContext.equipment.Where(e => !e.deleted);
List<int> locationRoleIdList = locationRoleIds.Select(id => int.Parse(id)).ToList();
result = result.Where(e => locationRoleIdList.Contains(e.eqp_ast_equipment_to_location.Any(el => el.eqp_equipment_location_role_id)));

我遇到了一个错误

el.eqp_equipment_location_role_id

声明“无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型”

eqp_equipment_location_role_id 是一个整数,我正在检查整数列表是否包含该数字。我不明白问题是什么。

提前致谢。

【问题讨论】:

  • 不应该eqp_equipment_location_role_id 返回一个bool(因为它是一个Any),但顾名思义它是一个int,或者至少不是一个bool
  • 此外,Contains 检查 元素,而不是集合,或 bool 本身(是的,bool 可以元素),但这可能不是你想要的。
  • 现在解决这个问题很困难。 eqp_ast_equipment_to_location 是什么?你能分享你的(相关的)类定义吗?

标签: c# linq lambda


【解决方案1】:

Contains 采用值而不是 lambda。因此,e.eqp_ast_equipment_to_location.Any(el =&gt; el.eqp_equipment_location_role_id) 不是int 类型的有效项。

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.contains?view=netframework-4.7.2#System_Collections_Generic_List_1_Contains__0_

也许:

result = result.Where(e => e.eqp_ast_equipment_to_location.Any(el => locationRoleIdList.Contains(el.eqp_equipment_location_role_id)));

更接近预期?

【讨论】:

  • 是的,这就是我的意图。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多