Sorting nested collections

Lets say we retrieve data which has nested property which is a collection(customer entity having bunch of orders). there are many ways to sort the returned collection of orders.

here is one way

we will have some code like below to get the list of customers, where we are including the Orders also, instead of changing the methods we could you CollectionViewSource to do the sorting

public IQueryable GetCustomers()
{
return this.ObjectContext.Customers.Include(“Orders”);
}

In the following sample, we are binding the collectionviewsource to the selected customers orders collection and sorting by orderdate, and binding ordersDatagrid to the CollectionViewSource

 we get the customers using

ctx.Load<Customer>(ctx.GetCustomersQuery(), (lo) => { customers = lo.Entities.ToList(); datagrid1.ItemsSource = customers; }, null);

  <UserControl.Resources>
        <CollectionViewSource x:Name=”cvs” Source=”{Binding ElementName=datagrid1, Path=SelectedItem.Orders}”>
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName=”OrderDate” Direction=”Descending”/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
       
    </UserControl.Resources>

    <Grid x:Name=”LayoutRoot” Background=”White”>
        <Grid.RowDefinitions>
            <RowDefinition Height=”*”/>         
            <RowDefinition Height=”Auto”/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <my:DataGrid x:Name=”datagrid1″ IsReadOnly=”True” Grid.Row=”0″ Grid.Column=”0″></my:DataGrid>                
        <my:DataGrid x:Name=”ordersDatagrid” ItemsSource=”{Binding Source={StaticResource cvs}}” Grid.Column=”1″/>
     
    </Grid>

Advertisements

3 thoughts on “Sorting nested collections

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s