[英]Cannot convert from 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.IEnumerable<int?>'
class first
{
private int? firstID;
}
class second
{
private int secondID;
private int secondField;
}
public override Expression<Func<first, bool>> FirstFilter()
{
Contex db = new Contex();
List<second> list = (from p in db.second select p).ToList();
return b => list.Select(p => p.secondID).Contains(b.firstID);
}
and I have error: 我有错误:
cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'
无法从“ System.Collections.Generic.IEnumerable”转换为“ System.Collections.Generic.IEnumerable”
I have tried many different ways, but I just don't know how can I fix it. 我尝试了许多不同的方法,但是我不知道该如何解决。
Use this: 用这个:
list.Select(p => p.secondID).Cast<int?>().Contains(b.firstID);
You are getting the problem, because list.Select(p => p.secondID)
will be an IEnumerable<int?
您遇到了问题,因为
list.Select(p => p.secondID)
将是IEnumerable<int?
, but because firstID is int
(non-nullable), overload resolution cannot determine a valid overload of Contains to call. ,但是因为firstID是
int
(不可为空),所以重载解析无法确定要调用的Contains的有效重载。 You cannot implicitly convert from IEnumerable<int?>
to IEnumerable<int>
. 您不能从
IEnumerable<int?>
隐式转换为IEnumerable<int>
。 The Cast extension method works by casting each element to int. Cast扩展方法通过将每个元素都转换为int来工作。
As mentioned in another answer, you could also simply pass in a non-nullable int into Contains: 如另一个答案中所述,您还可以将一个不可为null的int传递给Contains:
list.Select(p => p.secondID).Contains(b.firstID ?? 0);
But, do be aware that this might not be want. 但是,请注意,这可能不是必需的。 If the first list contains
0
, and firstID
is null, the result will be true, because you pass in 0 when the value is null.The Cast version of the expression returns false when firstID
is null. 如果第一个列表包含
0
,并且firstID
为null,则结果为true,因为在值为null时firstID
当firstID
为null时,表达式的Cast版本返回false。
尝试提供一个默认值firstID
如果是空:
return b => list.Select(p => p.secondID).Contains(b.firstID ?? 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.