我有两个用于过滤数据列表的查询。主体部分每次都运行,正常情况下应该将结果总数减少到最多一两个。当我编辑一个 Foo
对象而不是创建一个新对象时,我还想从我正在处理的数据集中删除保存在数据库中的副本。
我目前正在使用 if 语句和第二个查询将其删除。有没有办法将条件和第二个查询组合到第一个查询中?
IEnumerable<Foo> myFoos = bar.GetFoos()
.Where(f => f.Value1 == value1 && f.Value2 == value2);
if (editFoo != null)
myFoos = myFoos.Where(f => f.ID != editFoo.ID);
当我尝试 sehe 或 Dan Seaver 建议的查询,并在 myFoos
上调用 .ToList()
时,我得到一个异常:
Unable to create a constant value of type 'Foo'. Only primitive types ('such as Int32, String, and Guid') are supported in this context
我创建了虚拟对象,其中包含我未修改的查询中的每个属性,并且它运行时没有错误,所以我倾向于怀疑问题是 Entity Framework 不理解所提出的查询中的空检查并且是吐在他们身上。 Entity Framework 是罪魁祸首;没有它,任何一种解决方案都将按书面方式工作。
最佳答案
bool 逻辑来拯救。
IEnumerable<Foo> myFoos = bar.GetFoos()
.Where(f =>
(f.Value1 == value1) &&
(f.Value2 == value2) &&
((editFoo == null) || (f.ID != editFoo.ID)));
让它工作的是shortcut evaluation
关于c# - 是否可以将条件 LINQ 查询组合成每次都运行的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8218381/