【问题标题】:Map Enum to user choice checkboxes将枚举映射到用户选择复选框
【发布时间】:2017-12-25 17:16:19
【问题描述】:

目前我有以下

if ((int)dpRepeatType.SelectedValue == (int)Constants.RepeatType.Weekly)
{
                 wrule = new WeeklyRecurrenceRule(Convert.ToDateTime(dtDateStart.Value),WeekDays.Monday, 1);
                _newAppointment.RecurrenceRule = wrule.ToString();

}

在屏幕上,我有 7 个复选框代表一周中的几天。周日到周六我的问题是 WeekDay 是 Telerik rad 调度程序的内部枚举,基于以下内容。

我的问题不是在单个复选框上使用 if 语句来查看用户选择的哪一天或哪一天可以多于一个,我目前如何使用 linq 执行此操作我正在使用 if 语句执行此操作但我相信有更好的方法。

[Flags]
    public enum WeekDays
    {
        //
        // Summary:
        //     Specifies none of the days
        None = 0,
        //
        // Summary:
        //     Specifies the first day of the week
        Sunday = 1,
        //
        // Summary:
        //     Specifies the second day of the week
        Monday = 2,
        //
        // Summary:
        //     Specifies the third day of the week
        Tuesday = 4,
        //
        // Summary:
        //     Specifies the fourth day of the week
        Wednesday = 8,
        //
        // Summary:
        //     Specifies the fifth of the week
        Thursday = 16,
        //
        // Summary:
        //     Specifies the sixth of the week
        Friday = 32,
        //
        // Summary:
        //     Specifies the work days of the week
        WorkDays = 62,
        //
        // Summary:
        //     Specifies the seventh of the week
        Saturday = 64,
        //
        // Summary:
        //     Specifies the weekend days of the week
        WeekendDays = 65,
        //
        // Summary:
        //     Specifies every day of the week
        EveryDay = 127
    }
}

这就是我想要实现的用户界面。

【问题讨论】:

    标签: c# .net linq checkbox enums


    【解决方案1】:

    假设您的表单中唯一的CheckBox 控件是与工作日相关的控件,并且它们的Name 属性遵循以下模式:

    CheckBoxMonday
    CheckBoxTuesday
    ...
    

    一种解决方案可能是以下一种:

    WeekDays wd = WeekDays.None;
    
    foreach (CheckBox checkBox in this.Controls.OfType<CheckBox>())
    {   
        if (checkBox.IsChecked)
            wd |= (WeekDays)Enum.Parse(typeof(WeekDays), checkBox.Name.Replace("CheckBox", ""));
    
    }
    

    演示代码here.

    【讨论】:

    • 感谢您今天回答我如何将其变成工作日,或者一开始的转换是否会这样做
    • 如果表单上的其他复选框类型的控件在这种情况下不会失败。
    • 转换已经返回一个 WeekDays 枚举,并根据选定的复选框设置了正确的标志。
    • 如果您的表单中有其他复选框,最好在它们的名称中定义一个通用模式,以便您可以正确选择它们。您可以添加诸如“WD_CheckBoxMonday”之类的前缀,这样您就知道必须选择名称以“WD_”开头的那些。
    • 使用LINQ,您也可以使用以下一个衬里:List&lt;WeekDays&gt; wds = this.Controls.OfType&lt;CheckBox&gt;().Where(x =&gt; x.IsChecked).Select(x =&gt; (WeekDays)Enum.Parse(typeof(WeekDays), x.Name.Replace("CheckBox", ""))).ToList();,但您仍然需要将它们合并到一个单独的标志枚举中。
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多