Make relative string according to selected options from checkboxlist in asp.net

I am creating a practice management system where I need to add a function where a clinic or hospital can add visitors to their clinics or hospitals. The following is the mu current interface.enter image description here

Here, the clinic or hospital selects the day and time so that all selected days receive this time. Now I want to create a string in which the values ​​will be stored as follows

Mon, Wed, Fri
10.00 - 2.00pm

I can execute the above line with this code

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;

, , .. , , . , 2 , , .

-
10:00 - 02:00

. , , , , .

+4
1

, , - - , 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();
}
0

Source: https://habr.com/ru/post/1649853/


All Articles