Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run correct method based on file name (C#)

I'm checking name of the file and return TRUE if it's correct:

bool name_FORD = file.Contains("FORD"); 
bool name_KIA  = file.Contains("KIA");  
bool name_BMW  = file.Contains("BMW");

Based on this I want to have switch and run correct method. But I confused how to correctly do it:

switch (true)
{
 case 1 name_FORD: 
              method1();
              break();
 case 2 name_KIA:
              method2();
              break();
 case 3 name_BMW:
              method3();
              break();
}
like image 472
4est Avatar asked Sep 13 '26 23:09

4est


1 Answers

I suggest organizing all strings and corresponding methods as a Dictionary:

Dictionary<string, Action> myCars = new Dictionary<string, Action>() {
  {"FORD", method1}, // e.g. {"FORD", () => {Console.WriteLine("It's Ford!");}},
  { "KIA", method2},
  { "BMW", method3}, 
  //TODO: Put all the cars here
};

then we can put a simple loop:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value();                // we execute corresponding method pair.Value

    break; 
  }

Edit: In case we can have complex methods (e.g. method may want file and key parameters) we can change signature:

// Each action can have 2 parameters: key (e.g. "FORD") and file
Dictionary<string, Action<string, string>> myCars = 
  new Dictionary<string, Action<string, string>>() {
     {"FORD", (key, file) => {Console.Write($"{key} : {string.Concat(file.Take(100))}")}}, 
     { "KIA", (key, file) => {Console.Write($"It's {key}!")}},
     { "BMW", (key, file) => {/* Do nothing */}}, 
  //TODO: Put all the cars here
};

When executing in the loop, we should provide these parameters:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value(pair.Key, file); // we execute corresponding method pair.Value

    break; 
  }
like image 93
Dmitry Bychenko Avatar answered Sep 15 '26 13:09

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!