简体   繁体   中英

C# - match many cases in a single run

So the case is this:

The user can provide a group of strings for a propert. ex:

DaysNeeded ="Sunday,Tuesday,Friday,Saturday";

In the actual UI, the days of the week are available as check boxes. I'm trying to provide a way so that the user can also set the days needed in the code behind through a property.

Now my query is, which strategy is the best way to execute certain pieces of code that are respective to the days that the user have provided. Meaning, the DaysNeeded property has sunday,Tuesday, Friday and Saturday. Each day has certain piece of code to be executed. If i have to have a forloop with a switch case for each day of the week, i feel it would cost more as i have to run the for loop, the number of days the user has given.

Is there a way that i can run a single code that matches all the set of days the user has given and run the respective code pieces?

Please let me know if I'm not clear with my query.

Running four -- or more -- iterations of a for loop isn't going to be a problem, but it's unnecessary.

if (DaysNeeded.Contains("Sunday"))
    DoSundayWork();

if (DaysNeeded.Contains("Tuesday"))
    DoTuesdayWork();

if (DaysNeeded.Contains("Friday"))
    DoFridayWork();

if (DaysNeeded.Contains("Saturday"))
    DoSaturdayWork();

By the way, it would probably make more sense to use a Flags enum for your DaysNeeded property rather than a comma-delimited string.

Dictionary<string, Action> actions = new Dictionary<string, Action>() {
   {"Monday", e=> ...},
   ...
   {"Sunday", e=> ...}

}

foreach (var day in actions.Keys ) {
 if (DaysNeeded.Contains(day) {
   actions[day].Invoke()
 }
}

Maybe you like that.

I'm not sure I fully understand your question but would it work if you write your switch statement without breaks.

eg

switch(condition)
{
  case "Monday":
     ...
  case "Tuesday":
     ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM