Search code examples
c#sortingcomparetoicomparable

Sorting List with Custom Control


I want to sort a list that contains custom control. The list has a list of listboxitem that have content with a checkbox inside, and the checkbox has a textblock inside.

List<ListBoxItem> listboxItem =new List<ListBoxItem>();

Some code that add the control into listboxItem with for loop
{
ListBoxItem lbi = new ListBoxItem();
CheckBox chkBox = new CheckBox();
TextBlock txtBlock = new TextBlock();
txtBlock.Text = sometext;
chkBox.Content = txtBlock;
lbi.Content = chkBox;
listBoxItems.Add(lbi); 
}

listboxItems.Sort();

And I have implement IComparable interface

public int CompareTo(Object obj)
    {
        if (obj == null) return 1;

        List<ListBoxItem> listBoxItems = obj as List<ListBoxItem>;

        for (int i = 0; i < listBoxItems.Count; i++)
        {
            if (i < listBoxItems.Count)
            {
                ListBoxItem listBoxItem = listBoxItems[i];
                ListBoxItem lbi = this.listBoxItems[i];
                CheckBox checkBox = listBoxItem.Content as CheckBox;
                CheckBox chk = lbi.Content as CheckBox;
                TextBlock textBlock = checkBox.Content as TextBlock;
                TextBlock txt = chk.Content as TextBlock;

                return string.Compare(txt.Text, textBlock.Text);
            }
        }
        return 0;
    }

And it still give me error that need to implement Icomparable. Not sure is it implement or use correctly, pretty new to me for this implementation @.@


Solution

  • Just found out that can use Linq and Tag to get rid of IComparable.

    Edited Code:

    Some code that add the control into listboxItem with for loop
    {
    ListBoxItem lbi = new ListBoxItem();
    CheckBox chkBox = new CheckBox();
    TextBlock txtBlock = new TextBlock();
    txtBlock.Text = sometext;
    chkBox.Content = txtBlock;
    lbi.Content = chkBox;
    lbi.Tag = sometext;
    listBoxItems.Add(lbi); 
    }
    
    listBoxItems = listBoxItems.OrderBy(x => x.Tag).ToList();
    

    Then, the list will be sort in alphabetic perfectly.