Reputation: 255
I want to be able to check if the string contains all the values held in the list; So it will only give you a 'correct answer' if you have all the 'key words' from the list in your answer. Heres something i tired which half fails;(Doesn't check for all the arrays, will accept just one). Code i tired:
foreach (String s in KeyWords)
{
if (textBox1.Text.Contains(s))
{
correct += 1;
MessageBox.Show("Correct!");
LoadUp();
}
else
{
incorrect += 1;
MessageBox.Show("Incorrect.");
LoadUp();
}
}
Essentially what i want to do is:
Question: What is the definition of Psychology?
Key words in arraylist: study,mental process,behaviour,humans
Answer: Psychology is the study of mental process and behaviour of humans
Now if and ONLY if the answer above contains all key words will my code accept the answer. I hope i have been clear with this.
Edit: Thank you all for your help. All answers have been voted up and i thank everyone for quick answers. I voted up the answer that can be easily adapted to any code. :)
Upvotes: 14
Views: 10082
Reputation: 9002
This should help:
string text = "Psychology is the study of mental process and behaviour of humans";
bool containsAllKeyWords = KeyWords.All(text.Contains);
Upvotes: 6
Reputation: 62484
Using LINQ:
// case insensitive check to eliminate user input case differences
var invariantText = textBox1.Text.ToUpperInvariant();
bool matches = KeyWords.All(kw => invariantText.Contains(kw.ToUpperInvariant()));
Upvotes: 20
Reputation: 19842
You can use some of the LINQ methods like:
if(Keywords.All(k => textBox1.Text.Contains(k))) {
correct += 1;
MessageBox.Show("Correct");
} else {
incorrect -= 1;
MessageBox.Show("Incorrect");
}
The All
method returns true when the function returns true for all of the items in the list.
Upvotes: 3