tags:

views:

46

answers:

2

Hello,

I have an ObservableCollection of Task objects. Each Task has the following properties:

  • AssignedTo
  • Category
  • Title
  • AssignedDate

I'm giving the user an interface to select which of these fields they was to sort by. In some cases, a user may want to sort by up to three of these properties. How do I dynamically build a LINQ statement that will allow me to sort by the selected fields in either ascending or descending order?

Currently, I'm trying the following, but it appears to only sort by the last sort applied:

var sortedTasks = from task in tasks
                  select task;

if (userWantsToSortByAssignedTo == true)
{
  if (sortByAssignedToDescending == true)
    sortedTasks = sortedTasks.OrderByDescending(t => t.AssignedTo);
  else
    sortedTasks = sortedTasks.OrderBy(t => t.AssignedTo);
}

if (userWantsToSortByCategory == true)
{
  if (sortByCategoryDescending == true)
    sortedTasks = sortedTasks.OrderByDescending(t => t.Category);
  else
    sortedTasks = sortedTasks.OrderBy(t => t.Category);    
}

Is there an elegant way to dynamicaly append order clauses to a LINQ statement?

+2  A: 

You can use ThenBy instead of OrderBy to apply more than one ordering. You will need an OrderBy(x => 1) at the beginning to start the process though.

var sortedTasks = from task in tasks
                  orderby 1
                  select task;

if (userWantsToSortByAssignedTo)
{
    if (sortByAssignedToDescending)
        sortedTasks = sortedTasks.ThenByDescending(t => t.AssignedTo);
    else
        sortedTasks = sortedTasks.ThenBy(t => t.AssignedTo);
}

if (userWantsToSortByCategory)
{
    if (sortByCategoryDescending)
        sortedTasks = sortedTasks.ThenByDescending(t => t.Category);
    else
        sortedTasks = sortedTasks.ThenBy(t => t.Category);
}
Mark Byers
A: 

Can you use the following

sortedTasks = sortedTasks.OrderBy(t => t.AssignedTo).ThenBy(t => t.Category);
simon_bellis