【问题标题】:How can l use Regex.Replace method within LINQ我如何在 LINQ 中使用 Regex.Replace 方法
【发布时间】:2018-03-31 08:23:02
【问题描述】:

我有一个控制器,使用以下方法 getMail()

public JsonResult getMail(string id)
{
    int Id = Convert.ToInt32(id);
    string pattern = @"\bmem_id\b";
    string replace = "100";         
    var result = (from a in db.tblmail_type
                  where a.Id == Id                              
                  select new MailModel
                  {
                      subject = a.Subject,
                      Content = Regex.Replace(a.Content, pattern, replace);
                  });
    return Json(result, JsonRequestBehavior.AllowGet);
}

此方法用于获取邮件内容。在获取内容之前,我想将邮件内容中的“mem_id”替换为“100”。默认内容如下:

Content = "您已成功注册会员ID:mem_id"

我在 LINQ 中使用了Regex.Replace() 方法。但是这段代码不会改变内容。当我将此代码更改为下面给出的这种形式时,它可以正常工作。

public JsonResult getMail(string id)
{
    int Id = Convert.ToInt32(id);
    var input = db.tblmail_type.Where(x=>x.Id==Id).FirstOrDefault().Content;
    string pattern = @"\bmem_id\b";
    string replace = "100";            
    string content = Regex.Replace(input, pattern, replace);
    var result = (from a in db.tblmail_type
                  where a.Id == Id
                  select new MailModel
                  {
                      subject = a.Subject,
                      Content = content
                  });
    return Json(result, JsonRequestBehavior.AllowGet);
}

为什么会这样?任何人都可以指定这个奇怪问题背后的原因吗?如何替换 LINQ 中的“内容”?

【问题讨论】:

  • 第一种方法是替换每封邮件。第二种方法是替换所有邮件。正则表达式不在循环中。
  • db.tblmail_type的类型是什么?我怀疑问题可能是在第一种情况下您的Regex.Replace 正在数据库中执行,这可能有不同的正则表达式规则。
  • @Jon Skeet,我在数据库中名为 tblmail_type 的表中存储了不同类型的邮件。如何替换 linq 查询中的内容。你有什么解决办法吗?
  • 这仍然不是db.tblmail_type 的编译时类型。如果将鼠标悬停在 VS 上会显示什么?我们根本不知道您是如何访问数据库的。
  • 感谢@jon skeet 为我花费了宝贵的时间。

标签: c# regex asp.net-mvc linq


【解决方案1】:

您可以使用以下任何一种解决方案,

解决方案 1:

很遗憾,您将无法将正则表达式处理逻辑直接发送到数据库。 您需要从数据库中获取Content,然后遍历列表并应用正则表达式。 这可以通过使用AsEnumerable() 来完成。它将查询分为两部分。 第一部分是inside part(AsEnumerable() 之前的查询)作为Linq-to-SQL 执行。 第二部分是outside part(AsEnumerable() 之后的查询)作为Linq-to-Objects 执行。 第一部分在数据库上执行,所有数据都被带到客户端。 第二部分(这里是选择)在客户端执行。 所以简而言之,AsEnumerable() 运算符将查询处理移至客户端。

var result = ( from a in db.tblmail_type.AsEnumerable()
               where a.Id == Id
               select new MailModel {
                        subject = a.Subject,
                        Content = Regex.Replace(a.Content, pattern, replace)
              });

解决方案 2:

var result = db.tblmail_type.Where(x => x.Id == Id).AsEnumerable().Select(x => new MailModel { Content = Regex.Replace(x.Content, pattern, replace) , subject = x.Subject}).ToList();
    

解决方案 3:

 var result = db.tblmail_type.Where(x => x.Id == Id).ToList();
 result.ForEach(x => x.Content = Regex.Replace(x.Content, pattern, replace));

【讨论】:

  • 感谢您的详细解释。这三种解决方案非常有效!
猜你喜欢
  • 2017-05-29
  • 1970-01-01
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多