linq查询其中int ID属于List <int>

Sla*_*abo 8 c# linq list

我遇到了linq查询的问题.我以前用过类似的东西,但我现在无法理解可能出现的问题.

错误

'System.Collections.Generic.List.Contains(int)'的最佳重载方法匹配有一些无效的参数
Argument'1':无法从'int?'转换 'int'; 是指rTestResults的where子句

码:

List<int> rMTCPlates = (from rP in mDataContext.Plates
                        where rP.SOItem.SONumberID == aSONumber
                        select rP.ID).ToList();

var rTestResults = from rT in mDataContext.TestSamplesViews
                   where rMTCPlates.Contains(rT.PlateID)
                   select rT;  
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

任何帮助表示感谢,
谢谢

ben*_*wey 21

您可以在此处使用null-coalescing运算符:

var rTestResults = from rT in mDataContext.TestSamplesViews 
               where rMTCPlates.Contains(rT.PlateID ?? 0) 
               select rT; 
Run Code Online (Sandbox Code Playgroud)


Shi*_*mmy 6

这是因为ID字段可以为空,而集合中的项不是.

您可能忘记在数据库中将其标记为非null,因此设计人员以这种方式生成它.

DB中最好的标记是非空并刷新数据.

此外,U没有指定你正在使用哪个LINQ,假设你使用了linq,我不确定Contains扩展方法在Linq to Sql或Linq to Entities中是否有效,即使修复了上述问题,你也可能会得到另一个NotSupportedException.

因此,要么使用两个查询,第一个用于访问数据库,第二个用于从已加载的集合中检索您的值,还是考虑使用Lint to Entities的'Contains()'变通方法?.

如果你正在使用linq-to对象而你并不关心上面描述的所有垃圾,只需使用以下内容:

var rTestResults = from rT in mDataContext.TestSamplesViews  
                   where rT.PlateID.HasValue &&
                       rMTCPlates.Contains(rT.PlateID.Value)  
                   select rT.Value; 
Run Code Online (Sandbox Code Playgroud)