开发者

if else condition in windows phone 7

I am trying to do something like a if else condition in C#.

My below code is to check that all the text in text block is correct and show a display message.

if ((correctAns.Contains(textBlock1.Text)) && 
    (correctAns.Contains(textBlock2.Text)) && 
    (correctAns.Contains(textBlock3.Text)) && 
    (correctAns.Contains(textBlock4.Text)) && 
    (correctAns.Contains(textBlock5.Text)))
  {
      //If it contains the correct answer
      MessageBox.Show("All correct开发者_开发百科");
  }

What i want for now is to check if any 3 of the text in the text block is correct will show a message box.

How should i go about doing it?


It might be easier to put all the textboxes in an array and use Linq to count:

if (textboxes.Where(tb => correctAns.Contains(tb.Text)).Count() >= 3)
{
    // show message
}

This way it is much easier to add or remove textboxes to this check.


Count them.

If your code matches the entire problem, this is probably the most straight-forward - but if the number of text blocks grow, you might want to re-think the solution:

int count = 0;

if (correctAns.Contains(textBlock1.Text)) count++;
if (correctAns.Contains(textBlock2.Text)) count++;
if (correctAns.Contains(textBlock3.Text)) count++;
if (correctAns.Contains(textBlock4.Text)) count++;
if (correctAns.Contains(textBlock5.Text)) count++;

if (count >= 3)
{
   MessageBox.Show("At least 3 correct");
}


If you want any three in any combination, writing out a single conditional block to cover everything will be pretty rigid and non-flexible. It will be better to count them, then check the count.

int count = 0;
if (correctAns.Contains(textBlock1.Text))
    ++count;
if (correctAns.Contains(textBlock2.Text))
    ++count;
if (correctAns.Contains(textBlock3.Text))
    ++count;
if (correctAns.Contains(textBlock4.Text))
    ++count;
if (correctAns.Contains(textBlock5.Text))
    ++count;

if (count >= 3) {
    // Show message.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜