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");
}
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) ...
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With