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();
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With