none
How to change an if else statement to a switch statement RRS feed

  • Question

  • I am moving files from one folder to another folder because the folder has subfolders I am using an if statement to check if the file name contains certain characters that differentiate that file from others in order to move it to the correct new folder. How would I go about making this a switch statement?

    if ( path.Contains("9") ) 
    	File.Copy ( Path.Combine ( fName , path), Path.Combine(path9, fName  ) , true ) ;
    	else if ( fileName.Contains( "3") ) 
    	File.Copy ( Path.Combine ( fName , path) , Path.Combine ( path3 , fName ) , true );
    	else if ( fileName.Contains( "6" ) )
    	File.Copy ( Path.Combine ( fName , path) , Path.Combine ( path6 , fName ) , true );
    	else if ( fileName.Contains ( "0" ) )
    	File.Copy ( Path.Combine ( fName , path ) , Path.Combine ( path0 , fName ) , true );
    Thank you



    CuriousCoder

    Wednesday, July 18, 2018 12:50 PM

Answers

  • Hello,

    Perhaps a Dictionary could be an option for you. First time thru "path 9 goes here", second time  "path 6 goes here". Of course if there is a chance the path may not exists e.g. path is 10 then you need to check the Dictionary with ContainsKey assertion.

    string path = "9";
    
    var dict = new Dictionary<string, string>()
    {
        {"9","path 9 goes here"},
        {"3","path 3 goes here"},
        {"6","path 6 goes here"},
        {"0","path 0 goes here"}
    };
    
    Console.WriteLine(dict[path]);
    
    path = "6";
    Console.WriteLine(dict[path]);
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, July 18, 2018 1:31 PM
    Moderator

All replies

  • Hello,

    Perhaps a Dictionary could be an option for you. First time thru "path 9 goes here", second time  "path 6 goes here". Of course if there is a chance the path may not exists e.g. path is 10 then you need to check the Dictionary with ContainsKey assertion.

    string path = "9";
    
    var dict = new Dictionary<string, string>()
    {
        {"9","path 9 goes here"},
        {"3","path 3 goes here"},
        {"6","path 6 goes here"},
        {"0","path 0 goes here"}
    };
    
    Console.WriteLine(dict[path]);
    
    path = "6";
    Console.WriteLine(dict[path]);
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Wednesday, July 18, 2018 1:31 PM
    Moderator
  • The switch case statement is expecting one value to compare which is equivalent to the == compassion operator. The if condition is required as you already did to achieve this solution.

    Wednesday, July 18, 2018 4:27 PM
  • Check this too:

    switch( "360".FirstOrDefault( fileName.Contains ) )

    {

    case '3':

       // . . .

       break;

    case '6':

       // . . .

       break;

    case '0':

       // . . .

       break;

    default:

       // . . .

       break;

    }

    Wednesday, July 18, 2018 4:50 PM
  • Rules pattern could be used too or it is template pattern maybe.
    class abstract Rule
    {
        protected abstract string Path{get;}
        public Copy(string fName, string path)
        {
            File.Copy(Path.Combine(fName, path), Path.Combine(Path, fName), true);
        }
        public abstract bool IsMatch(string value);
    
    class Rule9 : Rule
    {
        protected override string Path => "path9";
        public override bool IsMatch(string value)
        {
            return value.Contains("9");
        }
    }
    class Rule3 : Rule
    {
        protected override string Path => "path3";
        public override bool IsMatch(string value)
        {
            return value.Contains("3");
        }
    }
    class Rule6 : Rule
    {
        protected override string Path => "path6";
        public override bool IsMatch(string value)
        {
            return value.Contains("6");
        }
    }
    class Rule0 : Rule
    {
        protected override string Path => "path0";
        public override bool IsMatch(string value)
        {
            return value.Contains("0");
        }
    }
    class MyClass
    {
    ....
        public class Copy(string fName, string path)
        {
            List<Rule> rules = new List<Rule>
            {
                new Rule9();
                new Rule6();
                new Rule3();
                new Rule0();
            }
            foreach(Rule r in rules)
            {
                if(r.IsMatch(path))
                    r.Copy(fName, path);
            }
        }
    }
    Sorry for path/Path but I think it is clear. A few information to good naming.
    Thursday, July 19, 2018 9:49 AM
  • Thank you for the suggestions, I am going to try them all today, will post the answer as soon they are complete.

    Thanks again.


    CuriousCoder

    Thursday, July 19, 2018 10:21 AM
  • using System;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;

    namespace CONVERTIFTOSWITCH
    {
        class Program
        {
            static void Main(string[] args)
            {
                int pathdigit=Test("Testfile",@"E:\Applicant9");
                switch(pathdigit)
                {
                    case 9:
                        File.Copy(Path.Combine("fName", "path"), Path.Combine("path9", "fName"), true);
                        break;
                    case 6:
                        File.Copy(Path.Combine("fName", "path"), Path.Combine("path6", "fName"), true);
                        break;
                }
            }

            public static int Test(string fName,string path)
            {
                //if (path.Contains("9"))
                //    File.Copy(Path.Combine(fName, path), Path.Combine(path9, fName), true);
                //else if (fileName.Contains("3"))
                //    File.Copy(Path.Combine(fName, path), Path.Combine(path3, fName), true);
                //else if (fileName.Contains("6"))
                //    File.Copy(Path.Combine(fName, path), Path.Combine(path6, fName), true);
                //else if (fileName.Contains("0"))
                //    File.Copy(Path.Combine(fName, path), Path.Combine(path0, fName), true);


                var resultString = Regex.Match(path, @"\d+").Value;

                int number = int.Parse(resultString);
                return number;
               
            }
        }
    }
    Thursday, July 19, 2018 10:54 AM
  • There's nothing particularly wrong with a series of if/else if statements.  Unless the switch statement has more than 8 or 10 choices, the compiler will generate a series of if/else if sequences for it anyway.

    Tim Roberts | Driver MVP Emeritus | Providenza &amp; Boekelheide, Inc.

    Thursday, July 19, 2018 4:52 PM
  • Just as reference, a switch statement can be made out of an if else like this:

    let x be any variable, for this example x will be an int;

    if(x == 5)
    {
        do this;
    }
    else if(x == 6)
    {
        do that;
    }
    else
    {
        do everything else;
    }

    to convert this to a swtich statement, simply make this transition:

    switch (x)
    {
        case 5:
            do this;
            break;
        case 6:
            do that;
            break;
        default:
            do everything else;
    }
    In the case of default, that is you "else" and covers everything the case's don't. Hope this helps!

    Tuesday, July 24, 2018 7:46 PM