开发者

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.

e.g.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜