Shubham Sahu
Shubham Sahu

Reputation: 2015

Automatically Sort ListBox Items (A to Z or 1 to 9 serial wise)

I have a ListBox on my WP 8.1 Silverlight app that looks like this:

<StackPanel Grid.Column="1" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Top">                
    <ListBox x:Name="FavoriteListBox" Visibility="Collapsed" 
             SelectionChanged="FavoriteListBox_SelectionChanged"
             HorizontalAlignment="Stretch"
             VerticalAlignment="Top" Opacity="1"
             Background="{StaticResource PhoneBackgroundBrush}" Foreground="{StaticResource PhoneForegroundBrush}"
             Height="300" Width="250">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Visibility="Visible" x:Name="FavoriteListBoxTextBlock"  
                       FontSize="35" Foreground="Black" Text="{Binding AnswerName}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

In my ListBox the items should look like this:

  1. item1
  2. item2
  3. to 15.....

However currently it is not in the order of 1,2,3,4... Instead it is in order of when the item is added.

I want the ListBox items to serialize automatically. How can this be achieved?

Upvotes: 0

Views: 414

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39082

If you want to sort a list or array before serializing, you can use two different solutions.

Arrays have a static Array.Sort method, that sorts the items of the array in-place (sorts the contents of the instance itself).

For lists and other collections you can use LINQ's OrderBy extension method.

var sortedList = list.OrderBy( 
    item => item.PropertyToOrderBy )
    .ToList();

Note, that the original list is left intact, the result of the ToList() extension method is a new instance.

Upvotes: 2

Related Questions