Ziema
Ziema

Reputation: 45

How do I sort a list of checkboxes by their name?

I have a foreach loop which fills a list with checkboxes from a groupbox. Problem is that they are added in a random order. Since I named them all in an ascending alphabetical order I want to sort them by their Name propery.

I've already tried using .Sort() but it doesn't do anything. Also I tried using a Linq expression DigBoxes = DigBoxes.OrderBy(x => x.Name).ToList();

But it also doesn't do anything...

Here's my code:

GroupBox box = (GroupBox)e.Argument;
string DigInput = "";
List<CheckBox> DigBoxes = new List<CheckBox>();

foreach (Control c in box.Controls)
{
    if(c is CheckBox)
    {
        DigBoxes.Add(c as CheckBox);
    }
}
DigBoxes = DigBoxes.OrderBy(x => x.Name).ToList();

Upvotes: 0

Views: 738

Answers (2)

Broots Waymb
Broots Waymb

Reputation: 4826

I'm going off of some information you provided in a comment about numbers being in the name, so I may or may not be off here..
Depending on how many you have, you will definitely see a problem. Sorting by Name is a straight string comparison, that is, it doesn't take numerical values into account the same way.

For example, suppose your collection consists of CheckBox_7 and CheckBox_10. If you want those in numerical order, you'd expect 7 to come before 10. This isn't the case with strings. At index 9 of each name we have a 7 and a 1. 7 is obviously larger, which means as a whole, "CheckBox_7" is going to come after "CheckBox_10".

If you want to take the numerical values into account, you'll need to parse the name and add a little extra intelligence into a custom sort method.
Here's one question with something similar. It might be a good starting point for your specific case: sort string-numbers

Upvotes: 2

johannesr
johannesr

Reputation: 21

Have you tried something like this:

var items = CheckBoxList1.Items
            .Cast<ListItem>()
            .OrderBy(i=>i.Text)
            .ToArray();
        CheckBoxList1.Items.Clear();
        CheckBoxList1.Items.AddRange(items);

Upvotes: 0

Related Questions