Sorting Tasks by Name
When working with project data using Aspose.Tasks for .NET, it’s often necessary to organize tasks in a specific order for analysis or display. One common approach is sorting tasks alphabetically by their names. This guide explains how to do that by implementing a custom comparer.
Implementing a Custom Comparer
To sort tasks by name, define a class that implements the IComparer<Task>
interface. This comparer checks for null or empty names and then applies a string comparison:
1private class TaskNameComparer : IComparer<Task>
2{
3 public int Compare(Task x, Task y)
4 {
5 if (string.IsNullOrEmpty(x.Get(Tsk.Name)))
6 return 1;
7 if (string.IsNullOrEmpty(y.Get(Tsk.Name)))
8 return -1;
9 return x.Get(Tsk.Name).CompareTo(y.Get(Tsk.Name));
10 }
11}
This logic ensures tasks without names are placed at the end of the list.
Collecting and Sorting Tasks
Load a project and collect its tasks using ChildTasksCollector
. Then apply the custom comparer to sort them:
1Project project = new Project("New Project.mpp");
2ChildTasksCollector coll = new ChildTasksCollector();
3TaskUtils.Apply(project.RootTask, coll, 0);
4List<Task> tasks = coll.Tasks;
5
6tasks.Sort(new TaskNameComparer());
7
8foreach (Task task in tasks)
9{
10 Console.WriteLine(task);
11}
The ChildTasksCollector
helps flatten the task hierarchy into a list, making it easier to work with. After sorting, tasks will appear in alphabetical order based on their names.
Summary
Sorting tasks by name can simplify reporting, filtering, and UI rendering. With a simple custom comparer and the task collection utilities in Aspose.Tasks, this process is easy to integrate into .NET workflows.