微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 根据asp.net中checkboxlist中的选定选项创建相对字符串

我正在制作实践管理系统,我需要添加功能,诊所或医院可以在诊所或医院中添加访问医生.以下是mu current interface.

enter image description here

诊所或医院选择日间和医院.把时间放在一起让所有选定的日子都到了.现在我想创建一个字符串,其中值存储如下

星期一,星期三,星期五
上午10点 – 下午2点

我可以用这段代码执行上面的字符串

string selectedDays = string.Empty;
foreach (ListItem chk in daySelect.Items) {
    if (chk.Selected == true) {
        selectedDays += chk.Text + ",";
    }
}

string vistingDays = string.Empty;
vistingDays = selectedDays + "<br />" + frmTime.SelectedValue.ToString + "-" + ToTime.SelectedValue.ToString;

如果连续选择天数,即Mon Tue Wed Thu那么它应该得到这样的字符串值.这里唯一不同的是,如果他们选择超过2天连续,那么而不是逗号它将破折号作为分隔符.

周一至周四
上午10点 – 下午2点

我希望帮助我的代码执行上述操作.请原谅我的帖子是否比我在这里发布的方式复杂,但我真的需要帮助.

解决方法

不是最可读的解决方案,但是它有效,如果有人使用LINQ或更少的代码有一些聪明的解决方案我很乐意看到它,但如果没有其他人回答你,欢迎使用我的代码,只需针对所有可能的场景进行正确测试:

protected void btnSave_Click(object sender,EventArgs e)
{
    string selectedDays = String.Empty;
    int j = 0;

    var items = new Dictionary<int,string>();

    for (int i = 0; i < daySelect.Items.Count; i++)
        items.Add(i,daySelect.Items[i].Selected ? daySelect.Items[i].Text : "");

    for (int i = 0; i < items.Count; i++ )
    {
        string current = items.ElementAt(i).Value;

        if(String.IsNullOrEmpty(selectedDays))
        {
            j = items.ElementAt(i).Key;
            selectedDays = current;
            continue;
        }
        else if(current != "")
        {
            if((j + 1) == i)
            {
                int lastComma = selectedDays.LastIndexOf(',');
                int lastDash = selectedDays.LastIndexOf('-');

                if ((selectedDays.Contains('-') && !selectedDays.Contains(',')) || lastDash > lastComma)
                {
                    string day = selectedDays.Substring(selectedDays.LastIndexOf('-') + 1,3);
                    selectedDays = selectedDays.Replace(day,current);
                }
                else
                    selectedDays += ("-" + current);

                j = items.ElementAt(i).Key;
            }
            else
            {
                selectedDays += "," + current;
                j = items.ElementAt(i).Key;
            }
        }
    }

    string vistingDays = selectedDays + "<br />" + frmTime.SelectedValue.ToString() + "-" + ToTime.SelectedValue.ToString();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐