Question

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");
              }
Was it helpful?

Solution

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) ...

OTHER TIPS

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");
}

Essentially this problem is solved by designing things a bit differently.

What you really want is to run some sort of rule validation over some input, so then I'd probably create something a bit more general like that, and then each rule would contain a nice set of properties that it wishes to check for. You'd then call this from a generic sort of 'run rules against input' stage of processing the data.

It sounds a little bit over-the-top, perhaps, but in general it's nice to do things like this so you are prepared for changes.

In the end (in the specific rule itself) you'd clearly have an implementation a bit like yours, but probably written in a shorter way, like BrokenGlass has shown.

Add each string to a List<string> and then iterate through each with a foreach statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top