Search code examples
c#checkboxlistalphabetized

How do I alphabetize the items in two different CheckBoxLists?


I have two checkboxes (Recommended and Others) which have peoples names (concatenated, i.e. John Smith is one item). I want to alphabetize the selected members of each list into one. How can I do this?


Solution

  • An ASP.NET implementation with three checkboxlist controls (chkRecommended, chkOthers, chkCombined)

    var listItems = (from ListItem listItem in chkRecommended.Items
                     where listItem.Selected
                     select listItem)
                    .Union(from ListItem listItem in chkOthers.Items
                           where listItem.Selected
                           select listItem)
                    .OrderBy(listItem => listItem.Text);
    
    chkCombined.Items.Clear();
    foreach (ListItem listItem in listItems)
        chkCombined.Items.Add(listItem);
    

    If you just meant a list of the values rather than another control, you can modify the original query I provided or extend it like so

    var listValues = listItems.Select(listItem => listItem.Value);