Search code examples
c#if-statementcompare

Comparing Text with a lot of If/else


I have variables which search specific words between two words

> string number207 = FindTextBetweenWithout(fileTTT, "\n207 ", " 20");
> string number208 = FindTextBetweenWithout(fileTTT, "\n208 ", " 20");
> string number209 = FindTextBetweenWithout(fileTTT, "\n209 ", " 20");
> string number219 = FindTextBetweenWithout(fileTTT, "\n219 ", " 20"); 

After i have a text file which contain numbers:

>207
>208
>209
>1402
>132

This numbers read with this method

 var listChrt = File.ReadAllText(textBox2.Text); 

So after i tried to compare this numbers

        string compare()
        {
            if (listChrt.Contains("207"))
            {
                return number207;        
            }
            if (listChrt.Contains("208"))
                {
                return number208;
            }
            if (listChrt.Contains("1402"))
             {
                return number1402;
             } 

            return " ";
        }

and i tried pass it into TextBox

 richTextBox1.Text = (
              dss()
                   );

But only get first return line which is number207.

As i undestood if else statement ends when it find true, but i need something to iterate through all my text file and find compares to my existed varibles(string number207,208 etc)


Solution

  • When your code calls compare(), it checks if the list contains "207". If it does, it returns that value; the method stops there.

    If you really wanted to do it this way, you could create Booleans above that method's scope that check if the value has been found yet. If it has, you could have it go to the next part of the method. You'd need to use Boolean logical operators for that; check if listChrt contains a value AND the value has already been found.

    Though, this code is messy already. Your code would be a bit simpler if you were to pass in the values to compare against as arguments. Something like this:

    string compare(string baseValue, string valueToCompareAgainst)
     {
           if (baseValue.Contains(valueToCompareAgainst)
              {
                 return valueToCompareAgainst;
              }
           else
             {
                 return " ";
             }
     }
    

    You could then call that method multiple times, supplying the baseValue string multiple times as well as the different values. Or, the better way would be to put all the values to compare against in a string[] array or List<string> and iterate over them.