C# Multiple Property Sort
Posted
by Ben Griswold
on Johnny Coder
See other posts from Johnny Coder
or by Ben Griswold
Published on Tue, 30 Mar 2010 19:14:25 +0000
Indexed on
2010/03/30
19:23 UTC
Read the original article
Hit count: 591
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.
© Johnny Coder or respective owner