【问题标题】:use regex mongo c# to find in list使用正则表达式 mongo c# 在列表中查找
【发布时间】:2015-12-14 09:37:47
【问题描述】:

我可以在一个函数中执行此操作,或者以一个查询的更简短方式来代替那个吗? 我正在尝试使用正则表达式接收电子邮件,但我需要检查列表中的每封电子邮件。

public ObjectId? GetEntityIdByEmail(string email)
{
    var projection = Builders<Entity>.Projection.Include(x=>x._id);
    var filter = Builders<Entity>.Filter.Regex("Email", new BsonRegularExpression(new Regex(email, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)));
    var id = _entitiesStorage.SelectAsSingleOrDefault(filter,projection);
    if (id == null)
        return null;
    return (ObjectId)id["_id"];
}

public List<ObjectId> GetEntitiesIdsByEmail(IList<string> emails)
{
    var result = new List<ObjectId>();
    foreach (var email in emails)
    {
        var id = GetEntityIdByEmail(email);
        if (id != null)
            result.Add(id.Value);
    }
    return result;
}

【问题讨论】:

    标签: c# regex mongodb driver


    【解决方案1】:

    您可以扩展您的正则表达式查询

    public async Task<List<ObjectId>> GetEntitiesIdsByEmail(IList<string> emails)
    {
         var regexFilter = "(" + string.Join("|", emails) + ")";
         var projection = Builders<Entity>.Projection.Include(x => x.Id);
         var filter = Builders<Entity>.Filter.Regex("Email",
               new BsonRegularExpression(new Regex(regexFilter, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)));
         var entities = await GetCollection().Find(filter).Project(projection).ToListAsync();
         return entities.Select(x=>x["_id"].AsObjectId).ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      相关资源
      最近更新 更多