Silverlight - C# and LINQ - Ordering By Multiple Fields
- by user70192
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?