c# - 我如何在 LINQ 中使用 Regex.Replace 方法

标签 c# regex asp.net-mvc linq

我有一个具有以下方法的 Controller 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 = "You have successfully registered with Member 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 中的“内容”?

最佳答案

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

解决方案 1:

不幸的是,您无法将正则表达式处理逻辑直接发送到数据库。 您需要从数据库中获取 Content,然后遍历列表并应用正则表达式。 这可以通过使用 AsEnumerable() 来完成。它将查询分为两部分。 第一部分是内部(AsEnumerable() 之前的查询)作为Linq-to-SQL 执行。 第二部分是外部部分(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));

关于c# - 我如何在 LINQ 中使用 Regex.Replace 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49585784/

相关文章:

C# regEx 表达式不匹配换行符

c# - Miniprofiler 中的渲染步骤发生了什么?

.net - 为什么 ASP.NET MVC 2.0 不是 .NET 4.0 BCL 的一部分?

c# - 如何注释 C# 函数以表明参数返回时不为 null

c# - 如何从 dll 文件中提取类的源代码?

php - 使用 php preg_replace_callback - 但替换整个字符串而不是每个子字符串

asp.net - asp.net ajax 控件可以用作纯客户端控件吗?

c# - PHP 命令 mysql_insert_id() 的等效 C#/SQLite 命令?

c# - 无法在 Windows 10 通用应用程序中接收推送通知

javascript - 如何使用正则表达式和 javascript 将 1 1/2 重新格式化为相当分数 HTML