As you can see in the snippet below, sorting is easy with Linq. Simply provide your OrderBy criteria and you’re done. If you want a secondary sort field, add a ThenBy expression to the chain. Want a third level sort? Just add ThenBy along with another sort expression.
var projects = new List<Project>
{
new Project {Description = "A", ProjectStatusTypeId = 1},
new Project {Description = "B", ProjectStatusTypeId = 3},
new Project {Description = "C", ProjectStatusTypeId = 3},
new Project {Description = "C", ProjectStatusTypeId = 2},
new Project {Description = "E", ProjectStatusTypeId = 1},
new Project {Description = "A", ProjectStatusTypeId = 2},
new Project {Description = "C", ProjectStatusTypeId = 4},
new Project {Description = "A", ProjectStatusTypeId = 3}
};
projects = projects
.OrderBy(x => x.Description)
.ThenBy(x => x.ProjectStatusTypeId)
.ToList();
foreach (var project in projects)
{
Console.Out.WriteLine("{0} {1}", project.Description,
project.ProjectStatusTypeId);
}
Linq offers a great sort solution most of the time, but what if you want or need to do it the old fashioned way?
projects.Sort ((x, y) =>
Comparer<String>.Default
.Compare(x.Description, y.Description) != 0 ?
Comparer<String>.Default
.Compare(x.Description, y.Description) :
Comparer<Int32>.Default
.Compare(x.ProjectStatusTypeId, y.ProjectStatusTypeId));
foreach (var project in projects)
{
Console.Out.WriteLine("{0} {1}", project.Description,
project.ProjectStatusTypeId);
}
It’s not that bad, right?
Just for fun, let add some additional logic to our sort. Let’s say we wanted our secondary sort to be based on the name associated with the ProjectStatusTypeId.
projects.Sort((x, y) =>
Comparer<String>.Default
.Compare(x.Description, y.Description) != 0 ?
Comparer<String>.Default
.Compare(x.Description, y.Description) :
Comparer<String>.Default
.Compare(GetProjectStatusTypeName(x.ProjectStatusTypeId),
GetProjectStatusTypeName(y.ProjectStatusTypeId)));
foreach (var project in projects)
{
Console.Out.WriteLine("{0} {1}", project.Description,
GetProjectStatusTypeName(project.ProjectStatusTypeId));
}
The comparer will now consider the result of the GetProjectStatusTypeName and order the list accordingly. Of course, you can take this same approach with Linq as well.