5

I want to implement a simple search in my application, based on search query I have. Let's say I have an array containing 2 paragraphs or articles and I want to search in these articles for related subject or related keywords I enter.

For example:

//this is my search query
string mySearchQuery = "how to play with matches";

//these are my articles
string[] myarticles = new string[] {"article 1: this article will teach newbies how to start fire by playing with the awesome matches..", "article 2: this article doesn't contain anything"};

How can I get the first article based on the search query I provided above? Any idea?

0

2 Answers 2

6

This would return any string in myarticles that contains all of the words in mysearchquery:

var tokens = mySearchQuery.Split(' ');
var matches = myarticles.Where(m => tokens.All(t => m.Contains(t)));

foreach(var match in matches)
{
    // do whatever you wish with them here
}
Sign up to request clarification or add additional context in comments.

3 Comments

You would probably want to do a case-insensitive compare if this technique is used (i.e. so Matches matches matches). ;)
do you know how does that compare, in terms of speed, with the use of regex ??
You can further improve this by using string.ToLower(). Then you don't have to worry about capitalization.
1

I'm sure you can fine a nice framework for string search, cause it's a wide subject, and got many search rules.

But for this simple sample, try splitting the search query with " ", for each word do a simple string search, if you find it, add 1 point to the paragraph search match, at the end return the paragraph with the most points...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.