2012-06-26 25 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)'