Reputation: 4460
I'm trying to find words in a List. I have an Array with words to search, I have a string with word to find and I have a List that I'm adding letters.
I want to find words contained in Array search, looking for in List wordsCollected.
How can I do this ?
I'm trying this.
private string[] search = {"CAKE", "COFFEE"}; //words to search
private string wordFind = "CAKE"; //word find
private List<String> wordsCollected = new List<string>(); //add letters
/** add letters - A B C D E F G H .... */
public void addWordsCollected(string p){
if(!wordsCollected.Contains(p)){
wordsCollected.Add(p);
}
}
/** check if wordFind is found */
public bool isWordFound(){
bool found = false;
for (int x = 0; x < wordsCollected.Count; x++){
found = wordsCollected[x].IndexOf(wordFind);
if(found >= 0){
break;
found = true;
}
}
return found;
}
}
Upvotes: 0
Views: 163
Reputation: 3816
One possibility is to use LINQ to look for a specific word inside an array of strings. But what if you instead consider accepting a string array for searching inside that other array of strings, which will give more a general solution (one word to search for, or many).
Here is some code I put up in LinqPad that should be much more compact than the code you listed here, by using LINQ, I have tested it inside LinqPad and if I have understood the problem you want to solve here, it might be a solution:
void Main()
{
string[] search = { "CAKE", "COFFEE", "TEA", "HONEY", "SUGAR", "CINNEMON" };
string[] wordsToFind = { "CAKE", "TEAPOT" };
List<String> wordCollected = search.Where(s => s == wordsToFind[0]).ToList();
wordCollected.Dump();
wordCollected = search.Where(x => wordsToFind.Any(w => w == x)).ToList();
wordCollected.Dump();
}
The code above first searches for the first word "CAKE", while the next code searches for "CAKE" and "TEAPOT", in the array search. Please note that the Dump method here is an extension method inside LinqPad for displaying the results. If you will use the code outside of LinqPad (which I guess you want), remove the two lines above of course. Also note that there is a probability that the Any operator is quicker than Contains, since this exits quicker? Am I correct here?
Upvotes: 1