c# - 如何在 find 中使用 where 进行复杂的搜索查询?
问题描述
我有一个包含列表的产品模型,我需要找到产品并根据语言对其进行过滤。
return Collection.Find(p => p.ProductValues.Where(pv => pv.Lang == lang)).toList();
我得到的错误是
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<TestMongodb.Entities.ProductValue>' to 'bool'
我的模型是
public class Product : BaseEntity
{
public Product(string price, string date, List<ProductValue> value) =>
(Price, Date, ProductValues) = (price, date, value);
public string Price { get; set; }
public string Date { get; set; }
[BsonElement("value")]
public List<ProductValue> ProductValues { get; set; }
}
和
public class ProductValue
{
public ProductValue(string lang, string name, string description) =>
(Lang, Name, Description) = (lang, name, description);
[BsonElement("lang")]
public string Lang { get; }
[BsonElement("name")]
public string Name { get; }
[BsonElement("description")]
public string Description { get; }
}
解决方案
代替Where()
, 使用Any()
,
return Collection.Find(p => p.ProductValues.Any(pv => pv.Lang == lang));
为什么Any()
结束了Where()
?
Where(<predicate>)
子句用于根据传递给它的谓词进行过滤。它返回一组新的过滤记录而不是true/false
值。
Any(<predicate>)
:如果谓词满足条件则Any()
返回。true/false
`
现在,Find 根据返回布尔值 true 的条件返回文档,而不是新列表。这就是我们使用Any()
而不是的原因Where()