首页 > 解决方案 > 过滤 IQueryable 会带回错误的结果

问题描述

我有一个接受IQueryable<T>作为参数的方法,称为attachments. 在此方法中,我在多个语句中进一步过滤查询if。所以我的代码如下:

if(firstCondition)
{
   attachments = attachments.Where(i => i.TestItemId == 1); //3 records in db
   DoWork(attachments);
}
if(secondCondition)
{
   attachments = attachments.Where(i => i.TestItemId == 2); //2 records in db
   DoWork(attachments);
}
...

我在里面DoWork();做:

foreach(var items in attachments)
{
   //write attachment name to file here
}

在数据库中,我总共有 5 条记录,在第一条if语句中我得到了适当的结果。但是在第二种if情况下,我在查询中得到 0 结果。有人可以告诉我哪里出错了。

请注意,两个 if 条件都为真。

标签: c#iqueryable

解决方案


您不应该为 firstCondition 分配附件,结果将按 2 个条件过滤:TestItemId == 1 && TestItemId == 2。=> 它总是返回空列表;


推荐阅读