Silverlight - C# and LINQ - Ordering By Multiple Fields
Posted
by user70192
on Stack Overflow
See other posts from Stack Overflow
or by user70192
Published on 2010-03-14T19:23:33Z
Indexed on
2010/03/14
19:25 UTC
Read the original article
Hit count: 267
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?
© Stack Overflow or respective owner