我从EWS获得了WeeklyPattern with DaysOfTheWeek。它在一个数组中可以是一天或多天。
我有一个名为DayOfWeekMask的Enum,我需要将Array转换为Enum。
当Weeklypatter包含“星期一,星期二”时
该函数应该返回:
return DayOfWeekMask.olMonday | DayOfWeekMask.olThursday ;
当每周计时器包含3天时,它应返回3个元素。
这可能吗?答案 0 :(得分:1)
假设您将字符串格式化为以逗号分隔的天数列表:
"Monday, Tuesday, Thursday"
你可以Split
将它变成一个字符串数组并解析每个元素:
var days = weekString.Split(',', StringSplitOptions.RemoveEmptyEntries);
DayOfWeekMask? result = null;
foreach (var day in days) {
var enumDayName = "ol" + day;
if (Enum.IsDefined(typeof(DayOfWeekMask), enumDayName)) {
result |= (DayOfWeekMask)Enum.Parse(typeof(DayOfWeekMask), enumDayName, true);
}
}
请注意,您需要为DayOfWeekMask
的每个元素定义值,以使ORing正常工作!
如果您的输入是DayOfTheWeekCollection
,那么您可以直接转换枚举值:
DayOfTheWeekCollection days; // get this from somewhere
foreach (var day in days) {
switch (day) {
case DayOfTheWeek.Monday:
result |= DayOfWeekMask.Monday;
break;
case DayOfTheWeek.Tuesday:
// etc.
}
}
答案 1 :(得分:1)
两个枚举中的名称非常相似(OlDaysOfWeek
只是将“ol”附加到名称的开头),因此我们可以利用它。
这会将DaysOfTheWeek
属性(DayOfTheWeek
值的集合)转换为OlDaysOfWeek
(DayOfWeekMask
属性上的类型),这似乎就是你所拥有的要求:
OlDaysOfWeek daysOfTheWeek =
weeklyPattern.DaysOfTheWeek
.Select(x => (OlDaysOfWeek) Enum.Parse(typeof (OlDaysOfWeek), "ol" + x))
.Aggregate((x, y) => x | y);
如果您的初始收藏集包含DayOfTheWeek.Tuesday
和DayOfTheWeek.Thursday
,则会输出相当于OlDaysOfWeek.olTuesday | OlDaysOfWeek.olThursday
的值。
答案 2 :(得分:0)
我不知道你的变量的确切格式,但这些内容是这样的:
return (WeeklyPattern.Contains( "Monday") ? DayOfWeekMask.olMonday : 0)
| (WeeklyPattern.Contains( "Tuesday") ? DayOfWeekMask.olTuesday : 0)
| (WeeklyPattern.Contains( "Wednesday") ? DayOfWeekMask.olWednesday : 0)
| (WeeklyPattern.Contains( "Thursday") ? DayOfWeekMask.olThursday : 0)
| (WeeklyPattern.Contains( "Friday") ? DayOfWeekMask.olFriday : 0);