过滤IQueryable会带来错误的结果

时间:2019-05-21 08:48:48

标签: c# 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个结果。有人可以告诉我我要去哪里了。

请注意两个条件均成立。

2 个答案:

答案 0 :(得分:2)

条件串联

问题出在分配上,导致Where子句的串联。

attachments = attachments.Where(i => i.TestItemId == 1);
attachments = attachments.Where(i => i.TestItemId == 2);

以下代码与上面的代码相同:

attachments.Where(i => i.TestItemId == 1).Where(i => i.TestItemId == 2);

如果您从两个if中都删除了attachments =,则不会有任何问题。

if(firstCondition)
{
   DoWork(attachments.Where(i => i.TestItemId == 1));
}

if(secondCondition)
{
   DoWork(attachments.Where(i => i.TestItemId == 2));
}

答案 1 :(得分:0)

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

相关问题