如何在C#中的一段文本中搜索短语?

时间:2012-06-26 16:20:20

标签: c# string linq full-text-search

例如,我有一些文本列表,每个文本看起来像这样:

  

我们更喜欢可以回答的问题,而不仅仅是讨论过。提供   细节。分享您的研究。如果您的问题是关于本网站的

我希望在文本列表中搜索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();
    }
}

5 个答案:

答案 0 :(得分: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,请执行以下操作:

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

答案 1 :(得分:3)

包含应该工作。

var strList = new List<String>();
string itemSearch = "string to search for";

foreach (string str in strList)
{
    if(str.Contains(itemSearch))
    {
        return str;
    }
}

答案 2 :(得分: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 :(得分:0)

有一些提到使用ToLower()作为contains方法 为了性能,你应该使用string.IndoexOf(“string”,StringComparison.OrdinalIgnoreCase)

如果OP需要他的搜索不区分大小写

Case insensitive 'Contains(string)'

答案 4 :(得分:-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();
}
}