加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 21:01:23 所属栏目:百科 来源:网络整理
导读:我正在制作实践管理系统,我需要添加功能,诊所或医院可以在诊所或医院中添加访问医生.以下是mu current interface. 诊所或医院选择日间和医院.把时间放在一起让所有选定的日子都到了.现在我想创建一个字符串,其中值存储如下 星期一,星期三,星期五 上午10点 –
我正在制作实践管理系统,我需要添加功能,诊所或医院可以在诊所或医院中添加访问医生.以下是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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读