【问题标题】:How to use where inside a find for complex search queries?如何在 find 中使用 where 进行复杂的搜索查询?
【发布时间】:2021-10-01 13:04:19
【问题描述】:

我有一个包含列表的产品模型,我需要找到该产品并根据语言对其进行过滤。

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; }
    }

【问题讨论】:

  • 我不完全理解您的问题。 Find 返回匹配的第一个单个实例。你为什么要在单个实例上调用ToList

标签: c# mongodb linq


【解决方案1】:

Any()代替Where()

return Collection.Find(p => p.ProductValues.Any(pv => pv.Lang == lang));

为什么Any() 超过Where()

  • Where(&lt;predicate&gt;) 子句用于根据传递给它的谓词进行过滤。它返回一组新的过滤记录,而不是 true/false 值。

Any(&lt;predicate&gt;) :如果谓词满足条件,Any() 返回 true/false。 `

现在,Find 根据返回布尔值 true 的条件返回文档,而不是新列表。这就是我们使用Any() 而不是Where() 的原因

【讨论】:

  • 这不起作用我仍然有多种语言,我需要过滤列表,只获得正确的语言。示例:“productValues”:[ {“lang”:“ru”,“name”:“zzzz”,“description”:“string”},{“lang”:“en”,“name”:“xxxx”, "描述": "字符串" } ],
  • 您能否提供您期望的输入和输出
  • @AzadSamedov,正确的语言是什么意思,这里的正确语言是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
相关资源
最近更新 更多