Pickled Egg
Pickled Egg

Reputation: 123

Condense IF statement with several options?

I have a project I am working on which runs a process if a value is identified in a file

if (read_txt.Contains("one") == true)
   (do.something)
else if ((read_txt.Contains("two") == true)
   (do.something.else)
else
   (do.last.thing)

The (do.something) and (do.something.else) contains lots of things, like processes, if statements etc.

for example, (do.something) contains;

if (read_txt.Contains("one") == true)
   write_log
   process
   read_file
   if file.contains
        write_log
   else
        write_log
        process
   process
   if file.contains
        write_log
   else
        write_log

The issue I have is that if the file in 'read_txt' contains both "one" and "two", i want to be able to run both elements, (do.something) and (do.something.else), without copying the code out again as there is quite a bit.

What would be the best way to do this?

I am a beginner with C# but this project is helping me learn quite quickly!!

Upvotes: 0

Views: 1750

Answers (3)

JNYRanger
JNYRanger

Reputation: 7097

Write a function out of (do.something) and/or have your first if statement check for both being true at the same time such as:

if(read_txt.Contains("one") && read_txt.Contains("two"))

Upvotes: 0

Servy
Servy

Reputation: 203821

The issue I have is that if the file in 'read_txt' contains both "one" and "two", i want to be able to run both elements, (do.something) and (do.something.else), without copying the code out again as there is quite a bit.

That's easy, just don't make it an else if, just have two if statements.

bool foundNone = true;

if(read_txt.Contains("one"))
{
    DoFirstThing();
    foundNone = false;
}

if(read_txt.Contains("two"))
{
    DoSecondThing();
    foundNone = false;
}

if(foundNone)
{
   DoThirdThing();
}

This means it will run the code for each value found and won't stop when it finds one, but it still only does the last thing if none of the other options were hit.

Upvotes: 3

King King
King King

Reputation: 63317

bool not12 = true;
if (read_txt.Contains("one")) { (do.something); not12 = false;}
if (read_txt.Contains("two")) {(do.something.else); not12 = false;}   
if(not12) (do.last.thing);

Upvotes: 1

Related Questions