JimDel JimDel - 1 month ago 9
C# Question

My C# search function isn't finding key words when it should

I'm trying to perform a search for multiple key words. But even when I know it should find the word, it isn't.

private void btnSearch_Click(object sender, RoutedEventArgs e)
{
string[] SearchWords = txtSearchCriteria.Text.Split(' ');

string win810Words = "install setnetdir admin shortcuts";
string win7Words = "win 7 win7 windows7 vista";

string[] stringsToSearch = { "win810Words", "win7Words" };

foreach (var searchWord in SearchWords)
{
foreach (var item in stringsToSearch)
{
if (item.Contains(searchWord))
{
MessageBox.Show(searchWord + "found");
}
}
}
}


I know the problem is happening on the following line

if (item.Contains(searchWord))


because item.Contains in only looking at the name of the string "searchWord" and not the string itself. How can I get it to search the contents of the string, and not the name of the string?

Answer

Currently you're looking in the strings "win810Words" and "win7Words". There's an enormous difference between those string values and the values of the variables win810Words and win7Words.

So the first change is to use:

string[] stringsToSearch = { win810Words, win7Words };

Next, do you want it to match if the user only types part of a word, e.g. "dir" within "netdir"? If so, this is fine. If not, you should be splitting the "strings to search" on spaces as well, and look for the search words as exact matches (maybe case-insensitive) within the results.

Comments