2014-12-02 22 views
-1

我想創建一個替換函數,它可以替換我的linq查詢的「body」fieldname中的多個字符串。如何在linq中使用替換函數

這是我的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; 
    } 

我打電話上述功能,進入下面的 '的HttpResponse' 方法。

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時,主體內容數據不會被替換。因此該功能無法正常工作。 請告訴我,我可能會出錯的地方。

非常感謝

+2

不是解決你的問題,但你爲什麼要在'GetReplacedText()'中查詢'StoryTbls'?您正在尋找與'body'相匹配的'StoryTbls.Body'值,將其存儲在'data'中,然後再次不再使用它。看起來你可以刪除那部分。 – 2014-12-02 15:19:38

+2

用正則表達式解析(或替換)HTML是[壞主意](http://stackoverflow.com/a/1732454/1081897) – 2014-12-02 15:20:17

+0

'Body'屬性是否包含在'Body'屬性中? – faby 2014-12-02 15:20:19

回答

1

你需要從你的第一個調用的輸出到您的第二個電話來代替,並通過它來代替,像這樣:

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

謝謝你的回覆。這工作。 – user3070072 2014-12-02 15:26:14

相關問題