如何在linq中使用替换功能

时间:2014-12-02 15:14:26

标签: c# linq linq-to-sql asp.net-web-api

我正在尝试创建一个替换函数,它可以替换' body中的多个字符串。我的linq查询的fieldname。

这是我的linq功能:

  public string GetReplacedText(string body)
    {
        var data = from c in db.StoryTbls
                   where c.Body == body
                   select new
                   {
                      c.Body 
                   };

        Regex rgx2 = new Regex("<P align=right><A href>RS</A></P>");
        Regex rgx3 = new Regex("<A href>ML</A>");
        string res = rgx2.Replace(body, "");
        res = rgx3.Replace(body,"");
        return res;
    }

我正在调用上述功能,进入下面的&#39; httpresponse&#39;方法

    public HttpResponseMessage getData()
    {
        if (User.IsInRole("admin"))
        {
            Regex rgx2 = new Regex("<A href></A>");

            var join = (from s in db.StoryTbls
                        join c in db.META_Cat on s.Theme equals c.metaIndex
                        where s.ACTIVE == true
                        && s.PUB_ID == 250
                        && c.Categories == "RM"
                        orderby s.ACTIVEDATE descending
                        select new
                        {
                            s.TITLE,
                            s.Body,
                            s.ACTIVEDATE,
                            c.Categories

                        }).AsEnumerable().Select(c => new NewObj
                        {
                            Title = c.TITLE,
                            Body = GetReplacedText(c.Body),
                            ActiveDate = c.ACTIVEDATE,
                            Categories = c.Categories

                        }).Take(50).ToList();

            var data = join.ToList();

            if (!data.Any())
            {
                var message = string.Format("No data found");
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
            }

但是,当我调用API时,不会替换正文内容数据。因此功能不起作用。 请告知我可能出错的地方。

非常感谢

1 个答案:

答案 0 :(得分:1)

您需要将第一次调用的输出转换为Replace并将其传递给第二次Replace替换,如下所示:

string res = rgx2.Replace(body, "");
res = rgx3.Replace(res, "");