Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid writing every variation of a simple "if contains" statement for different strings

For example if in a textbox that is full of many different part numbers from a material list for computer parts, I only want one type of cat5 cable at any given time, and if two different types are seen, to warn the user. The cat5 cable part numbers could be: cat5PART#1, cat5PART#2, and cat5PART#3. So if only one cat5 part number is seen no worries, but as soon as two different types or more are seen, to warn. I could easily write it out manually three different times for each variation, but on a larger list of parts, it would take longer and risk mistakes. Plus I'd just love to know how programmers handle this type of function. I also don't know what it is called so I'm not sure how to google for it, despite knowing there are going to be many solutions for this exact situation out there so it is frustrating to have to bug people on a forum for something so simple.

An example of my code which obviously doesn't work because it would only warn if all three parts were detected not just if two were detected is below. I assume I'd use some variation of & and | or maybe it's something completely different?

Basically I don't want to have to write out on a larger scale

if contains part 1 and part 2

if contains part 1 and part 3

if contains part 2 and part 3

Thank you.

    if ((textBox2.Text.Contains("PART#1"))
      && (textBox2.Text.Contains("PART#2"))
      &&  (textBox2.Text.Contains("PART#3")))
              {
            MessageBox.Show("2 types of cat5 part numbers seen at the same time");
              }
like image 547
Saintjah Avatar asked Jan 20 '12 03:01

Saintjah


2 Answers

You can try this:

string[] parts = new [] {"PART#1", "PART#2", "PART#3"};
int count = parts.Count(s => textBox2.Text.Contains(s));
if (count >= 2) ...
like image 154
Sergey Kalinichenko Avatar answered Sep 28 '22 08:09

Sergey Kalinichenko


You can use Linq /Count() to test whether at least x strings you want to test are contained in textBox2.Text:

string[] parts = { "PART#1", "PART#2", "PART#3" };
if(parts.Count(s=> textBox2.Text.Contains(s)) >= 2)
{
   MessageBox.Show("2 types of cat5 part numbers seen at the same time");
}
like image 37
BrokenGlass Avatar answered Sep 28 '22 07:09

BrokenGlass