2012-06-26 62 views
0

例如,我有文本,每個文本看起來像這樣的列表:如何在C#中的文本中搜索短語?

我們更希望能回答的問題,而不僅僅是討論。提供 的詳細信息。分享您research.If你的問題是關於這個網站

,我想通過文字的列表來搜索can be answered並返回上面的文字爲具有can be answered文本。我應該怎麼做?

我試過Contains()但它什麼都沒有返回。我的代碼如下所示:

IEnumerable<App_ProjectTask> temp; 
if (!String.IsNullOrEmpty(query)) 
{ 
    temp = dc.App_ProjectTasks.Where(x => x.Title.Contains(query) || x.Description.Contains(query)); 
    if (temp.Count() > 0) 
    { 
     results = temp.ToList(); 
    } 
} 
+0

發佈一些代碼,將有助於 – Mangist

+0

顯示您代碼請爲您當前的測試..包含將答覆是/否,如果完全匹配被發現。 – BugFinder

+2

我想你想要的SubString功能 - http://www.dotnetperls.com/substring – JMK

回答

0

這個工作對我來說:這基本上是你做了什麼,但我發現我的課..

private void WriteLine(String text) 
    { 
     textBox1.Text += text + Environment.NewLine; 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     List<TestClass> list = new List<TestClass>(); 

     list.Add(new TestClass { Title = "101 unanswered questions", Description = "There are many questions which go unanswered, here are our top 1001" }); 
     list.Add(new TestClass { Title = "Best of lifes questions", Description = "Many of lifes questions answered" }); 
     list.Add(new TestClass { Title = "Top 10 smart answers", Description = "Top 10 smart answers for common interview questions" }); 

     var results = 
      list.Where(x => x.Description.Contains("answered questions") | x.Title.Contains("answered questions")); 
     foreach (TestClass res in results) 
     { 
      WriteLine(String.Format("Title: {0}, Desc: {1}", res.Title, res.Description)); 
     } 
    } 
} 

public class TestClass 
{ 
    public String Title; 
    public String Description; 
    public String Contents; 

    public TestClass() 
    { 
     Title = ""; 
     Description = ""; 
     Contents = ""; 
    } 
} 
3

Contains should be working。

+0

張貼此之前,你把代碼的問題。 – psych

+0

我會添加幾個ToLowers(),或爲ContainsIgnoreCase()創建一個擴展 – Ketchup

+0

取決於他是否正在尋找可能在多於一行的短語並且想要所有行的短語 – BugFinder

4
String text = "We prefer questions that can be answered, "+ 
       "not just discussed.Provide details. Share your research."+ 
       "If your question is about this website"; 
if (text.Contains("can be answered")) 
{ 
    Console.WriteLine("Text found"); 
} 

上面的代碼輸出Text found

要獲取所有String S作文本做這樣的事情:

var query = 
    from text in yourListOfTexts 
    where text.Contains("can be answered") 
    select text; 
+1

我會添加幾個ToLowers()或創建ContainsIgnoreCase()的擴展 – Ketchup

+2

@Ketchup你假設OP想要忽略大小寫。 – NominSim

+0

@NominSim但是,這是有道理的忽略案件...所以這是一個很好的提及如何避免這種情況。 –

-1

嘗試:

IEnumerable<App_ProjectTask> temp; 
if (!String.IsNullOrEmpty(query)) 
{ 
temp = dc.App_ProjectTasks.Where(x => x.Title.ToLower().Contains(query.ToLower()) || x.Description.ToLower().Contains(query.ToLower())); 
if (temp.Count() > 0) 
{ 
    results = temp.ToList(); 
} 
} 
0

有幾個提到使用ToLower將()爲contains方法的出於性能,你應該使用string.IndoexOf(「串」,StringComparison.OrdinalIgnoreCase)

即如果OP需要他的搜索是不區分大小寫

Case insensitive 'Contains(string)'